C++ Concurrency Guide std::launch

Launch is an enumeration type, used to start an asynchronous task, the parameters passed to the function async, its definition is as follows:

enum class launch {
    
    
	async = 0x1,
	deferred = 0x2
};

launch::async

launch::async means that a new thread will be created when the async function is called.

#include<iostream>
#include<future>

using namespace std;
 
class ThreadManage
{
    
    
public:
	int myThread(int num)
	{
    
    
		cout << "Thread start id = " << this_thread::get_id() << endl;
		chrono::milliseconds time(5000); //休息5秒
		this_thread::sleep_for(time);
		cout << "Thread end id = " << this_thread::get_id() << endl;
		return num *2;
	}
};
 
int main()
{
    
    
	ThreadManage manage;
	cout << "Main start id = " << this_thread::get_id() << endl;
	future<int> result = async(std::launch::async, &ThreadManage::myThread,&manage,5);
	cout << "continue......" << endl;
	cout << "result = " << result.get() << endl; //阻塞,等待线程myThread结束,获取返回。
    	return 0;
}

launch::deferred

Launch::deferred means delayed call. The entry function is executed only when the wait() or get() function in the future is called. (In fact, no new thread is created, it is the entry function called in the main thread, which is proved by printing the thread id below).
Change launch::async in the above example to launch::deferred to compare the differences between the two.

launch::async | launch::deferred

A new thread may be created, or the call may be delayed. The system will select the appropriate method according to the current resource situation.
When the launch parameter is not included, the function is the same as launch::async | launch::deferred. It is also possible to create a new thread or delay the call.

Guess you like

Origin blog.csdn.net/qq_24649627/article/details/114970146