1 -- std::future_status の使用
std::future_status メンバー関数には、timeout (実行タイムアウト)、ready (実行完了)、deferred (遅延実行) の 3 つの状態が含まれます。そのうち、遅延状態では、std::launch::deferred を使用してスレッドを遅延に設定する必要があります。 get() または wait() が呼び出されるまで。
#include <iostream>
#include <thread>
#include <mutex>
#include <future>
class Sample{
public:
// 线程入口函数
int thread(int value){
std::cout << "thread id: " << std::this_thread::get_id() << std::endl;
std::chrono::seconds dura(value); // rest
std::this_thread::sleep_for(dura);
return 5;
}
};
int main(int argc, char *argv[]){
Sample sample;
int value = 5;
std::cout << "thread id: " << std::this_thread::get_id() << std::endl;
std::future<int> result = std::async(&Sample::thread, &sample, value);
// 等待1s
std::future_status status = result.wait_for(std::chrono::seconds(1));
if (status == std::future_status::timeout){ // 超时,因为线程里面睡眠了5s
// if判断为true,表明线程还没执行完,超时了
std::cout << "thread timeout!" << std::endl;
}
else if(status == std::future_status::ready){ // 线程在等待期间成功返回
std::cout << "result.get(): " << result.get() << std::endl;
}
// std::launch::deferred设置延迟执行状态
// std::future<int> result = std::async(std::launch::deferred, &Sample::thread, &sample, value);
else if(status == std::future_status::deferred){ // 延迟执行状态
std::cout << "deferred, result.get(): " << result.get() << std::endl;
}
std::cout << "main thread continue ..." << std::endl;
return 0;
}
2 -- std::shared_future の使用
std::future オブジェクトは get() できるのは 1 回だけであるため (get() の実装は移動セマンティクスに基づいています)、複数のスレッドが std::future オブジェクト get() の結果を必要とする場合、エラーが発生します。
std::shared_future オブジェクトは上記の問題をうまく解決できます。
#include <iostream>
#include <thread>
#include <mutex>
#include <future>
// 线程入口函数
int thread(int value){
std::cout << "thread id: " << std::this_thread::get_id() << std::endl;
std::chrono::seconds dura(value); // rest
std::this_thread::sleep_for(dura);
return 5;
}
int main(int argc, char *argv[]){
// std::packaged_task 打包任务
std::cout << "thead id: " << std::this_thread::get_id() << std::endl;
std::packaged_task<int(int)> mypt(thread);
int value = 5;
std::thread thread1(std::ref(mypt), value);
thread1.join();
// std::future<int> result = mypt.get_future(); // std::future对象
std::shared_future<int> share_result(mypt.get_future()); // std::shared_future对象
// 可以多次调用
std::cout << "result.get(): " << share_result.get() << std::endl;
std::cout << "result.get(): " << share_result.get() << std::endl;
return 0;
}
3 -- std::atomic の使用
主なアイデア: