C++中的std::async如何为?

摘要:一、实例代码 问题 无论std::async调用了多少次,只额外单启动了一个线程,并且串行执行!待解惑 #include<iostream> #include<thread&
一、实例代码 问题 无论std::async调用了多少次,只额外单启动了一个线程,并且串行执行!待解惑 #include<iostream> #include<thread> #include <chrono> #include <future> //锁 static std::mutex s_mutex; static void sleepMine(int i) { std::thread::id threadId = std::this_thread::get_id(); //std::lock_guard<std::mutex> loock(s_mutex); std::cout << threadId << " Hello world" << i << " start." << std::endl; std::this_thread::sleep_for(std::chrono::seconds(i)); std::cout << threadId << " Hello world" << i << " end." << std::endl; } int main() { /*for (int i = 1; i <= 5; i++) { std::thread::id threadId = std::this_thread::get_id(); std::cout << threadId << " Main " << i << " end." << std::endl; std::async(std::launch::async, sleepMine, i); }*/ std::async(std::launch::deferred, sleepMine, 1).get(); std::async(std::launch::deferred, sleepMine, 2).get(); std::async(std::launch::deferred, sleepMine, 3).get(); std::cin.get(); }