C++ std::async of

  • 2020-11-26 18:57:03
  • OfStack

1. std::async function prototype:


template<class Fn, class... Args>
future<typename result_of<Fn(Args...)>::type> async(launch policy, Fn&& fn, Args&&...args);

Function: The second argument receives one callable object (affine, lambda expressions, class member functions, ordinary functions...) As parameters, and execute them asynchronously or synchronously.

For asynchronous or synchronous execution, it is determined by the execution policy of the first parameter:

(1) The callable object passed by std::launch::async executes asynchronously;

(2) The callable object passed by std::launch::deferred is executed synchronously;

std:: async ::async | std::launch::deferred can be asynchronous or synchronous, depending on the operating system, which we have no control over;

(4) If we do not specify a policy, it is equivalent to (3).

For the execution result:

We can use get, wait, wait_for, wait_until to wait for the end of the execution, the difference being that get can get the result of the execution. If the asynchronous execution strategy is selected, when calling get, if the asynchronous execution has not finished, get will block the current calling thread until the asynchronous execution has finished and get the result. If the asynchronous execution has finished, it will not wait for the execution result. If the synchronous execution strategy is chosen, the synchronous call is actually executed only when the get function is called, also known as the function call is deferred.

c, return result std::future

(1) deffered: The asynchronous operation has not started yet;

(2) ready: The asynchronous operation has been completed;

(3) timeout: Asynchronous operation timeout

Example 1 (asynchronous and synchronous execution) :


// STLasync.cpp :  This file contains  "main"  Function. This is where program execution begins and ends. 
//
 
#include "pch.h"
#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;
 
	// Get start time 
	system_clock::time_point start = system_clock::now();
 
	std::future<std::string> resultFromDB = std::async(std::launch::async, fetchDataFromDB, "Data");
 
	// Get data from a file 
	std::future<std::string> fileData = std::async(std::launch::deferred, fetchDataFromFile, "Data");
 
	// Know that call get function fetchDataFromFile To begin to implement 
	std::string FileData = fileData.get();
	// if fetchDataFromDB() The execution is not complete, get will 1 Blocks the current thread directly 
	std::string dbData = resultFromDB.get();
	
	// Get end time 
	auto end = system_clock::now();
 
	auto diff = duration_cast<std::chrono::seconds>(end - start).count();
	std::cout << "Total Time taken= " << diff << "Seconds" << std::endl;
 
	// The assembly data 
	std::string data = dbData + " :: " + FileData;
 
	// Output the assembled data 
	std::cout << "Data = " << data << std::endl;
 
	return 0;
}
 

Example 2 (query the status of future for the result of asynchronous execution) :


// STLasync.cpp :  This file contains  "main"  Function. This is where program execution begins and ends. 
//
 
#include "pch.h"
#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;
 
	// Get start time 
	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;
			// To get the results 
			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);
 
	
	// Get end time 
	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;
}
 

Output:

[

main start9096
fetchDataFromDB start7980
timeout...
timeout...
timeout...
timeout...
Ready...
DB_Data
Total Time taken= 5Seconds

]

Reference: https: / / www. ofstack. com article / 198765. htm

conclusion


Related articles: