目錄
1--std::async的使用
2--std::packaged_task的使用
3--std::promise的使用
1--std::async的使用
????????std::async用于啟動一個異步任務,并返回一個std::future對象;std::future對象里含有異步任務線程入口函數的結果;
????????std::launch::deferred 表示調用線程入口函數將會被延遲到 std::future 的 wait() 或 get() 調用,當 wait() 或者 get() 沒有被調用時,線程入口函數不會被調用(線程不會被創建);
#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::microseconds dura(value); // reststd::this_thread::sleep_for(dura);return 5;}};int main(int argc, char *argv[]){Sample sample;int value = 5000;// std::async用于啟動一個異步任務,并返回一個std::future對象// std::future對象里含有異步任務線程入口函數的結果std::cout << "thread id: " << std::this_thread::get_id() << std::endl;std::future<int> result = std::async(&Sample::thread, &sample, value);// std::launch::deferred 表示調用線程入口函數將會被延遲到 std::future 的wait()或get()調用// 當wait()或者get()沒有被調用時,線程入口函數不會被調用(線程不會被創建)// std::future<int> result = std::async(std::launch::deferred, &Sample::thread, &sample, value);// result.get()等待thread()執行完畢獲取結果后,主線程才繼續往下執行std::cout << "resule.get(): " << result.get() << std::endl; // result.wait() // 等待線程返回,但不返回結果std::cout << "main thread continue ..." << std::endl;return 0;
}
2--std::packaged_task的使用
????????std::packaged_task 用于打包任務,其包裝各種可調用對象,方便后續作為線程入口函數;
#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::microseconds dura(value); // reststd::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 = 5000;std::thread thread1(std::ref(mypt), value);thread1.join();std::future<int> result = mypt.get_future();std::cout << "result.get(): " << result.get() << std::endl;return 0;
}
3--std::promise的使用
????????std::promise 用于在其他線程中使用某個線程中的值;在下面的實例代碼中,thread2 使用了?thread1 中的 result 值;
#include <iostream>
#include <thread>
#include <mutex>
#include <future>// 線程入口函數
int thread(std::promise<int> &tmpp, int clac){clac++;clac *= 10; std::cout << "thread id: " << std::this_thread::get_id() << std::endl;int result = clac;tmpp.set_value(result);return 0;
}void thread_2(std::future<int> &tmpf){auto result2 = tmpf.get();std::cout << "tmpf.get(): " << result2 << std::endl;
}int main(int argc, char *argv[]){// std::promise 用于在某個線程中賦值,并在其他線程中將值取來用std::cout << "thead id: " << std::this_thread::get_id() << std::endl;std::promise<int> prom; int clac = 1;std::thread thread1(thread, std::ref(prom), clac);thread1.join();// 將promise中的值取來用std::future<int> result = prom.get_future();std::thread thread2(thread_2, std::ref(result));thread2.join();return 0;
}