c/c++ 多執行緒 等待一次性事件 std::promise用法
阿新 • • 發佈:2018-11-25
多執行緒 等待一次性事件 std::promise用法
背景:不是很明白,不知道為了解決什麼業務場景,感覺std::async可以優雅的搞定一切的一次等待性事件,為什麼還有個std::promise。
用法:和std::async一樣,也能夠返回std::future,通過呼叫get_future方法。也可以通過future得到執行緒的返回值。
特點:
1,是個模板類,模板型別是個方法型別,比如double(int),有一個引數,型別是int,返回值型別是double。
std::promise<int> pro;//pro.get_future.get()的返回值為int型別
2,在std::promise<T>的物件上,呼叫set_value後,future變成就緒(ready)狀態,呼叫future物件的get方法的地方就由阻塞變為不阻塞了。
std::promise<int> pro;
pro.set_value(10);
3,作為執行緒的引數時,必須用std::move轉成右值,否則編譯不過。
void thread1(std::promise<int> p, int val){ std::cout << "in thread1" << std::endl; p.set_value(val); } std::promise<int> pro; std::future<int> ft1 = pro.get_future(); std::thread t1(thread1, std::move(pro), 10); t1.detach(); std::cout << ft1.get() << std::endl;
4,std::promise的拷貝建構函式是被刪除了的,所以std::packaged_task作為函式的引數時,必須用std::move(pro),把它轉成右值引用。
程式碼:
#include <future> #include <thread> #include <iostream> void thread1(std::promise<int> p, int val){ std::cout << "in thread1" << std::endl; p.set_value(val); } int main(){ std::promise<int> p; std::future<int> f = p.get_future(); std::thread t1(thread1, std::move(p), 10); t1.detach(); std::cout << f.get() << std::endl; pthread_exit(NULL); }