std :: launch :: asyncとstd :: threadの違い

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

1.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進列挙型のシンボルであるため、操作を実行できます。OR操作を実行する場合、システムは状況に基づいてスレッドを遅延させるか、すぐに作成するかを選択することを意味します。
async()に起動パラメーターがない場合、システムはデフォルトで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)

L?
システムは、現在のメモリ環境とシステムの状態に応じて、非同期非同期(新しいスレッドを作成)で実行するか同期遅延(新しいスレッドを作成しない)で実行するかを決定しますしたがって、async()はthread()よりも難しいスレッドを作成し、システムクラッシュを引き起こし、プログラム操作の安定性を維持しやすくなります。

2:違い

1. async()は必ずしも新しいスレッドを作成するわけではなく、システムはそれ自体で判断します。thread()を作成する必要があります。
2. async()は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