1、std::async函数原型:
template<class Fn, class... Args> future<typename result_of<Fn(Args...)>::type> async(launch policy, Fn&& fn, Args&&...args);
功能:第二个参数接收一个可调用对象(仿函数、lambda表达式、类成员函数、普通函数......)作为参数,并且异步或是同步执行他们。
a、对于是异步执行还是同步执行,由第一个参数的执行策略决定:
(1)、std::launch::async 传递的可调用对象异步执行;
(2)、std::launch::deferred 传递的可调用对象同步执行;
(3)、std::launch::async | std::launch::deferred 可以异步或是同步,取决于操作系统,我们无法控制;
(4)、如果我们不指定策略,则相当于(3)。
b、对于执行结果:
我们可以使用get、wait、wait_for、wait_until等待执行结束,区别是get可以获得执行的结果。如果选择异步执行策略,调用get时,如果异步执行没有结束,get会阻塞当前调用线程,直到异步执行结束并获得结果,如果异步执行已经结束,不等待获取执行结果;如果选择同步执行策略,只有当调用get函数时,同步调用才真正执行,这也被称为函数调用被延迟。
c、返回结果std::future的状态:
(1)、deffered:异步操作还没有开始;
(2)、ready:异步操作已经完成;
(3)、timeout:异步操作超时。
实例1(异步执行和同步执行):
std::async的需求
假设我们必须从数据库和文件系统里里获取一些数据(字符串),然后需要合并字符串并打印。
在单线程中,我们这样做:
#include <iostream> #include <string> #include <chrono> #include <thread> using namespace std::chrono; std::string fetchDataFromDB(std::string recvData) { //确保函数要5秒才能执行完成 std::this_thread::sleep_for(seconds(5)); //处理创建数据库连接、获取数据等事情 return "DB_" + recvData; } std::string fetchDataFromFile(std::string recvData) { //确保函数要5秒才能执行完成 std::this_thread::sleep_for(seconds(5)); //处理获取文件数据 return "File_" + recvData; } int main() { //获取开始时间 system_clock::time_point start = system_clock::now(); //从数据库获取数据 std::string dbData = fetchDataFromDB("Data"); //从文件获取数据 std::string fileData = fetchDataFromFile("Data"); //获取结束时间 auto end = system_clock::now(); auto diff = duration_cast<std::chrono::seconds>(end - start).count(); std::cout << "Total Time taken= " << diff << "Seconds" << std::endl; //组装数据 std::string data = dbData + " :: " + fileData; //输出组装的数据 std::cout << "Data = " << data << std::endl; return 0; }
root@ubuntu:~/c++# ./async Total Time taken= 10Seconds Data = DB_Data :: File_Data root@ubuntu:~/c++#
于函数 fetchDataFromDB() 和 fetchDataFromFile()各自在单独的线程中运行5秒,所以,总共耗时10秒。
既然从数据库和文件系统中获取数据是独立的并且都要耗时,那我们可以并行地运行他们。
一种方式是创建一个新的线程传递一个promise作为线程函数的参数,并在调用线程中从关联的std::future对象获取数据
另一种方式就是使用std::async
使用函数指针调用std::async作为回调
修改上面的代码,并使用std::async异步调用fetchDataFromDB()
std::future<std::string>resultFromDB = std::async(std::launch::async, fetchDataFromDB, "Data"); std::string dbData = resultDromDB.get()
std::async()做如下的事情
·自动创建一个线程(或从内部线程池中挑选)和一个promise对象。
·然后将std::promise对象传递给线程函数,并返回相关的std::future对象
·当我们传递参数的函数退出时,它的值将被设置在这个promise对象中,所以最终的返回值将在std::future对象中可用
现在改变上面的例子,使用std::async异步地从数据库中获取数据
#include <iostream> #include <string> #include <chrono> #include <thread> #include <future> using namespace std::chrono; std::string fetchDataFromDB(std::string recvData) { //确保函数要5秒才能执行完成 std::this_thread::sleep_for(seconds(5)); //处理创建数据库连接、获取数据等事情 return "DB_" + recvData; } std::string fetchDataFromFile(std::string recvData) { //确保函数要5秒才能执行完成 std::this_thread::sleep_for(seconds(5)); //处理获取文件数据 return "File_" + recvData; } int main() { //获取开始时间 system_clock::time_point start = system_clock::now(); std::future<std::string> resultFromDB = std::async(std::launch::async, fetchDataFromDB, "Data"); //从文件获取数据 std::string fileData = fetchDataFromFile("Data"); //从DB获取数据 //数据在future<std::string>对象中可获取之前,将一直阻塞 std::string dbData = resultFromDB.get(); //获取结束时间 auto end = system_clock::now(); auto diff = duration_cast<std::chrono::seconds>(end - start).count(); std::cout << "Total Time taken= " << diff << "Seconds" << std::endl; //组装数据 std::string data = dbData + " :: " + fileData; //输出组装的数据 std::cout << "Data = " << data << std::endl; return 0; }
root@ubuntu:~/c++# g++ -std=c++11 async.cpp -o async -pthread root@ubuntu:~/c++# ./async Total Time taken= 5Seconds Data = DB_Data :: File_Data root@ubuntu:~/c++#
只使用了5秒
#include <iostream> #include <string> #include <chrono> #include <thread> #include <future> using namespace std::chrono; std::string fetchDataFromDB(std::string recvData) { std::cout << "fetchDataFromDB start" << std::this_thread::get_id() << std::endl; std::this_thread::sleep_for(seconds(5)); return "DB_" + recvData; } std::string fetchDataFromFile(std::string recvData) { std::cout << "fetchDataFromFile start" << std::this_thread::get_id() << std::endl; std::this_thread::sleep_for(seconds(3)); return "File_" + recvData; } int main() { std::cout << "main start" << std::this_thread::get_id() << std::endl; //获取开始时间 system_clock::time_point start = system_clock::now(); std::future<std::string> resultFromDB = std::async(std::launch::async, fetchDataFromDB, "Data"); //从文件获取数据 std::future<std::string> fileData = std::async(std::launch::deferred, fetchDataFromFile, "Data"); //知道调用get函数fetchDataFromFile才开始执行 std::string FileData = fileData.get(); //如果fetchDataFromDB()执行没有完成,get会一直阻塞当前线程 std::string dbData = resultFromDB.get(); //获取结束时间 auto end = system_clock::now(); auto diff = duration_cast<std::chrono::seconds>(end - start).count(); std::cout << "Total Time taken= " << diff << "Seconds" << std::endl; //组装数据 std::string data = dbData + " :: " + FileData; //输出组装的数据 std::cout << "Data = " << data << std::endl; return 0; }
root@ubuntu:~/c++# g++ -std=c++11 async.cpp -o async -pthread root@ubuntu:~/c++# ./async main start281473361022400 fetchDataFromFile start281473361022400 fetchDataFromDB start281473356628432 Total Time taken= 5Seconds Data = DB_Data :: File_Data root@ubuntu:~/c++#
查询future的状态获取异步执行的结果):
#include <iostream> #include <string> #include <chrono> #include <thread> #include <future> using namespace std::chrono; std::string fetchDataFromDB(std::string recvData) { std::cout << "fetchDataFromDB start" << std::this_thread::get_id() << std::endl; std::this_thread::sleep_for(seconds(5)); return "DB_" + recvData; } int main() { std::cout << "main start" << std::this_thread::get_id() << std::endl; //获取开始时间 system_clock::time_point start = system_clock::now(); std::future<std::string> resultFromDB = std::async(std::launch::async, fetchDataFromDB, "Data"); std::future_status status; std::string dbData; do { status = resultFromDB.wait_for(std::chrono::seconds(1)); switch (status) { case std::future_status::ready: std::cout << "Ready..." << std::endl; //获取结果 dbData = resultFromDB.get(); std::cout << dbData << std::endl; break; case std::future_status::timeout: std::cout << "timeout..." << std::endl; break; case std::future_status::deferred: std::cout << "deferred..." << std::endl; break; default: break; } } while (status != std::future_status::ready); //获取结束时间 auto end = system_clock::now(); auto diff = duration_cast<std::chrono::seconds>(end - start).count(); std::cout << "Total Time taken= " << diff << "Seconds" << std::endl; return 0; }
root@ubuntu:~/c++# ./async main start281473510387136 fetchDataFromDB start281473505993168 timeout... timeout... timeout... timeout... Ready... DB_Data Total Time taken= 5Seconds root@ubuntu:~/c++#
用Function对象作为回调调用std::async
#include <iostream> #include <string> #include <chrono> #include <thread> #include <future> using namespace std::chrono; /* * Function Object */ struct DataFetcher { std::string operator ()(std::string recvdData) { //确保函数要5秒才能执行完成 std::this_thread::sleep_for(seconds(5)); //处理获取文件数据 return "File_" + recvdData; } }; int main() { std::cout << "main start" << std::this_thread::get_id() << std::endl; //获取开始时间 system_clock::time_point start = system_clock::now(); std::future<std::string> resultFromDB = std::async(std::launch::async, DataFetcher(), "Data"); std::future_status status; std::string dbData; do { status = resultFromDB.wait_for(std::chrono::seconds(1)); switch (status) { case std::future_status::ready: std::cout << "Ready..." << std::endl; //获取结果 dbData = resultFromDB.get(); std::cout << dbData << std::endl; break; case std::future_status::timeout: std::cout << "timeout..." << std::endl; break; case std::future_status::deferred: std::cout << "deferred..." << std::endl; break; default: break; } } while (status != std::future_status::ready); //获取结束时间 auto end = system_clock::now(); auto diff = duration_cast<std::chrono::seconds>(end - start).count(); std::cout << "Total Time taken= " << diff << "Seconds" << std::endl; return 0; }
root@ubuntu:~/c++# ./async main start281473129901504 timeout... timeout... timeout... timeout... Ready... File_Data Total Time taken= 5Seconds
用lambda函数作为回调调用std::async
#include <iostream> #include <string> #include <chrono> #include <thread> #include <future> using namespace std::chrono; int main() { std::cout << "main start" << std::this_thread::get_id() << std::endl; //获取开始时间 system_clock::time_point start = system_clock::now(); std::future<std::string> resultFromDB = std::async([](std::string recvdData) { std::this_thread::sleep_for(seconds(5)); //处理创建数据库连接、获取数据等事情 return "DB_" + recvdData; }, "Data"); std::future_status status; std::string dbData; do { status = resultFromDB.wait_for(std::chrono::seconds(1)); switch (status) { case std::future_status::ready: std::cout << "Ready..." << std::endl; //获取结果 dbData = resultFromDB.get(); std::cout << dbData << std::endl; break; case std::future_status::timeout: std::cout << "timeout..." << std::endl; break; case std::future_status::deferred: std::cout << "deferred..." << std::endl; break; default: break; } } while (status != std::future_status::ready); //获取结束时间 auto end = system_clock::now(); auto diff = duration_cast<std::chrono::seconds>(end - start).count(); std::cout << "Total Time taken= " << diff << "Seconds" << std::endl; return 0; }
deferred... deferred... deferred... deferred... deferred... deferred... deferred... deferred... deferred... deferred... deferred... deferred... deferred... deferred... deferred... deferred... deferred... deferred... deferred... deferred... deferred... deferred... deferred... deferred... deferred... deferred... deferred... deferred... deferred... deferred... deferred... deferred... deferred... deferred... deferred... deferred... deferred... deferred... deferred... deferred... deferred... ^Cferred... root@ubuntu:~/c++# ^C root@ubuntu:~/c++# ./async
添加std::launch::async
std::future<std::string> resultFromDB = std::async(std::launch::async,[](std::string recvdData) { std::this_thread::sleep_for(seconds(5)); //处理创建数据库连接、获取数据等事情 return "DB_" + recvdData; }, "Data");
#include <iostream> #include <string> #include <chrono> #include <thread> #include <future> using namespace std::chrono; int main() { std::cout << "main start" << std::this_thread::get_id() << std::endl; //获取开始时间 system_clock::time_point start = system_clock::now(); std::future<std::string> resultFromDB = std::async(std::launch::async,[](std::string recvdData) { std::this_thread::sleep_for(seconds(5)); //处理创建数据库连接、获取数据等事情 return "DB_" + recvdData; }, "Data"); std::future_status status; std::string dbData; do { status = resultFromDB.wait_for(std::chrono::seconds(1)); switch (status) { case std::future_status::ready: std::cout << "Ready..." << std::endl; //获取结果 dbData = resultFromDB.get(); std::cout << dbData << std::endl; break; case std::future_status::timeout: std::cout << "timeout..." << std::endl; break; case std::future_status::deferred: std::cout << "deferred..." << std::endl; break; default: break; } } while (status != std::future_status::ready); //获取结束时间 auto end = system_clock::now(); auto diff = duration_cast<std::chrono::seconds>(end - start).count(); std::cout << "Total Time taken= " << diff << "Seconds" << std::endl; return 0; }
root@ubuntu:~/c++# g++ -std=c++11 async.cpp -o async -pthread root@ubuntu:~/c++# ./async main start281472903364032 timeout... timeout... timeout... timeout... Ready... DB_Data Total Time taken= 5Seconds