考虑如下代码:
#include <iostream> #include <string> #include <thread> #include <mutex> #include <condition_variable> std::mutex m; std::condition_variable cv; std::string data; bool ready = false; int result =0; void do_work() { std::this_thread::sleep_for(std::chrono::seconds(1)); result = 123; { std::lock_guard<std::mutex> lk(m); ready = true; } cv.notify_one(); } int main() { std::thread thread(do_work); thread.detach(); std::unique_lock<std::mutex> lk(m); cv.wait(lk, []{return ready;}); std::cout << "result=" << result << ‘\n‘; }
C++11引入了promise和future,可以使用task-based思维
#include <iostream> #include <cstdlib> #include <future> #include <chrono> void do_work(std::promise<int> promise){ std::this_thread::sleep_for(std::chrono::seconds(1)); promise.set_value(123); } int main() { std::promise<int> promise; std::future<int> future = promise.get_future(); std::thread thread( do_work , std::move(promise)); thread.detach(); future.wait(); std::cout << "result=" << future.get() << ‘\n‘; }
看看,是不是精简了很多代码?现在继续精简,用std::async代码如下:
#include <iostream> #include <cstdlib> #include <future> #include <chrono> int main() { std::future<int> future = std::async( [](){ std::this_thread::sleep_for(std::chrono::seconds(1)); return 123; }); future.wait(); std::cout << "result is " << future.get() << ‘\n‘; }
另外,介绍个C++在线编译器 https://wandbox.org/