std::thread和std::promise
Compared std::async
to std::thread
the original. thread will definitely create a new thread (rather than when it may not be created like async, and a new thread is created later (std::launch::deferred)), and the thread that creates it must also specify which strategy to wait for the new thread .
#include <iostream>
#include <thread>
void task() {
for (int i = 0; i < 10; i++) {
std::cout << "A";
}
}
int main() {
std::thread td(task);
for (int i = 0; i < 10; i++) {
std::cout << "B";
}
td.join();
system("pause");
return 0;
}
Here first std::thread td(task);
, a new thread is created to asynchronously output "A", and then the main thread outputs "B". td.join() is the so-called thread that created it. It must also specify which strategy to wait for the new thread . There are two strategies to choose from:
- std::thread.join() blocks until the child thread ends
- std::thread.detach() does not block. Let it play freely.
Althoughstd::thread.detach()
it is not necessary to block the main thread, if the main thread ends, these background tasks will be forcibly terminated. For example, your background is a download task, so there is almost no direct usedetach
, and it is all used with the synchronization mechanism behindstd::condition_variable
.
std::async
The high-level and low-level ones are also highlighted here std::thread
: in std::async
Chinese, we can implement synchronous waiting for its return value, that is, a std::future
simple call get()
, and even get the result of the task, but std::thread
not, waiting for the end of the child thread or getting the execution result of the child thread requires conditions Synchronization mechanisms such as variables.
std::promise
std::promise
Unique, it is used to transfer values between threads, which std::promise.set_value
is to set the value and std::promise.set_exception
set the exception. Note that the two cannot be set at the same time. std::promise.get_future
returns one std::future
. Because we set the value to always get it, the way to get it is get_future(), and then get():
#include <iostream>
#include <thread>
#include <future>
void task(std::promise<int>& p) {
std::cout << "Retrieve value from another thread:" << p.get_future().get() << "\n";
}
int main() {
std::promise<int> p;
std::thread td(task,std::ref(p));
std::this_thread::sleep_for(std::chrono::seconds(3));
std::cout << "Task in main thread accomplished...\n";
p.set_value(1024);
td.join();
system("pause");
return 0;
}
The program first outputs "Task in main thread accomplished..." and then "Retrieve value from another thread: 1024". In the task thread, p.get_future().get() will block the current thread until the promise has been set, that is, the task thread will block until the main thread executes
p.set_value(1024);
before continuing to execute.