1--std::async创建异步任务
std::async 创建一个异步任务,其不一定会创建一个新线程去执行该任务;
使用 std::launch::deferred 时,异步任务不会创建一个新线程;
使用 std::launch::async 时,操作系统会强制创建一个新线程来执行异步任务;
当 std::async 创建一个异步任务不显式指出使用 std::launch::deferred 或std::launch::async 时, 操作系统会随机采取一种方式来执行异步任务(当系统资源充足时,会优先创建一个新线程,否则就会延迟执行异步任务),可以使用 std::future_status 来判断异步任务处于哪种状态(等待0秒后判断);
#include <iostream>
#include <thread>
#include <future>int thread(){std::cout << "thread id: " << std::this_thread::get_id() << std::endl;return -1;
}int main(int argc, char *argv[]){std::cout << "thread id: " << std::this_thread::get_id() << std::endl;// std::future<int> result = std::async(std::launch::deferred, thread); //不会创建一个新线程std::future<int> result = std::async(std::launch::async, thread); //强制创建一个新线程std::cout << "result.get(): " << result.get() << std::endl;return 0;
}
使用 std::future_status 来判断异步任务处于哪种状态(等待0秒后判断);
#include <iostream>
#include <thread>
#include <future>int thread(){std::cout << "thread id: " << std::this_thread::get_id() << std::endl;return -1;
}int main(int argc, char *argv[]){std::cout << "thread id: " << std::this_thread::get_id() << std::endl;std::future<int> result = std::async(thread);std::future_status status = result.wait_for(std::chrono::seconds(0));if(status == std::future_status::deferred) { // 异步任务会延迟执行std::cout << "deferred running" << std::endl;std::cout << "result.get(): " << result.get() << std::endl;}else{ // 创建新线程来执行异步任务,还需进一步判断是否超时std::cout << "create new thread" << std::endl; }return 0;
}