Home > Enterprise >  Does deferred launch with std::async create a new thread or everything happening in the same thread
Does deferred launch with std::async create a new thread or everything happening in the same thread

Time:11-05

I have a piece of code (Lua to be specific) that is not thread safe but I want to emulate an async operation in it using deferred async (similar to a deferred promise). Is it safe to use std::launch::deferred and call wait from the same thread.

If the deferred async similar to creating something like this:

struct deferred_function {
  std::function<void()> fn;

  bool executed = false;

  void wait() {
    if (!executed) {
      fn();
      executed = true;
    }
  }
};

template<class T> auto create_deferred(T&& fn) {
    return deferred_function{ .fn = fn };
}

auto d1 = create_deferred([]() {
  std::cout << "Call 1d\n";
});

auto d2 = create_deferred([&d1]() {
  d1.wait();
  std::cout << "Call d2\n";
});

// Since d2 internally waits for d1 to be ready
// the order of waits here does not really matter
d2.wait();
d1.wait();

Godbolt: https://godbolt.org/z/KnM543vdT

CodePudding user response:

Yes, std::async(std::launch_policy::async, ...) will behave as if it is called in a new thread, std::async(std::launch_policy::deferred, ...) as if in the current thread.

https://en.cppreference.com/w/cpp/thread/async

Async invocation:

std::async calls INVOKE(decay-copy(std::forward(f)), decay-copy(std::forward(args))...) as if in a new thread of execution represented by a std::thread object.

...

Deferred invocation: Lazy evaluation is performed:

The first call to a non-timed wait function on the std::future that std::async returned to the caller will evaluate INVOKE(std::move(g), std::move(xyz)) in the current thread (which does not have to be the thread that originally called std::async), where ...

  • Related