0
Is it a thread execution for future promise
Hi Refer code having future and promise. Is this code a multithreaded ? When thread will execute the function in different thread ? The line when Getvalue is called from main thread ? If so, isn't this single thread ? Or Line where get() on future is called. https://sololearn.com/compiler-playground/cJYxmjXDhz83/?ref=app
1 Odpowiedź
0
Yes, using std::future and std::promise in C++ can be part of multithreaded code, but they don’t create threads on their own.
• If you’re using std::async(...), then a new thread may be created depending on the policy (std::launch::async or deferred).
• If you’re using std::promise and manually setting the value in another thread, then you are responsible for creating the thread using std::thread.
Example:
std::promise<int> p;
std::future<int> f = p.get_future();
std::thread t([&p]() {
p.set_value(42); // this runs in a separate thread
});
int value = f.get(); // blocks in main thread until value is set
t.join();
Here:
• The set_value is run in a separate thread.