std::launch::async和std::thread的不同之处

一.std::thread 和 std::launch::async

1.thread
我们在调用thread函数语句时,直接会在主线程中创建一个线程。
但是如果系统资源紧张,线程创建就会失败,执行thread()函数时整个程序可能会崩溃。

std::thread t1(gatewayFunction,paraofFunction);

2.async与deferred
而std::launch::async是创建一个异步任务,因为有时候async并不创建新线程,需要在调用该任务时,入口函数才会执行。

//async()默认参数为std::launch::async,
//任务已经创建,线程也强制创建,执行函数
std::future<int> result=std::async(gatewayFunction,para);
//进行各种运算。。。。。
cout<<result.get()<<endl;//得到任务计算后的返回值

其中std::launch::deferred更是

using namespace std:
//任务已经创建,线程不创建,不执行函数
std::future<int> result=std::async(launch::deferred,gatewayFunction,para);
//进行各种运算。。。。。
cout<<result.get()<<endl;//任务才被执行,调用入口函数,不创建新线程,得到任务计算后的返回值

async和deferred的不同之处是async强制任务创建新线程执行函数,而deferred不是,所以deferred是在调用处中延迟执行任务。与判断联合使用,可以防止线程过多导致系统崩溃。

3.async|deferred
async与deferred都是16进制枚举类型的符号,所以可以进行运算。 当进行或运算的时候,意味着系统将依据情况选择延迟或者立刻创建线程。
当async()中没有launch参数的时候,系统默认补充async|deferrred参数。系统会自行确定创建新线程还是延迟。

enum class launch {
    
     // names for launch options passed to async
    async    = 0x1,
    deferred = 0x2
};

async|deferred=0x1|0x2=0x3

std::future<int>result=std::async (launch::async|launch::deferred,gateF,para)

自行决定?
系统决定是异步async(创建新线程)还是同步deferred(不创建新线程)方式运行,取决于当时的内存环境,系统状态。所以async()比thread()硬创建线程,造成系统崩溃,更容易维护程序运行的稳定性。

二:不同之处

1.async()不一定创建新线程,系统自行判断,thread()一定创建。
2.async()可以通过future 获取到返回值。

如何自行判断?与 future的wait_for函数联合使用。

cout<<"This thread id is "<<_threadid<<endl;
std::future<int> result=std::async(launch::async|launch::deferred,mythread);

std::future_status status=result.wait_for(std::chrono::seconds(6));
//wait_for()里的参数可以是,5s,smin
//std::future_status status=result.wait_for(5min);

if(status==std::future::deferred)
{
    
    
	cout<<"The function running in this thread."<<_threadid<<endl;
}
else if(status==std::future::timeout)
{
    
    
	cout<<"The new thread is timeout"<<_threadid<<endl;
}
else if(status==std::future::ready)
{
    
    
	cout<<"The new thread is ready.""<<_threadid<<endl;
	cout<<result.get()<<endl;
}


猜你喜欢

转载自blog.csdn.net/guanxunmeng8928/article/details/108636339