c/c++ 多線程 等待一次性事件 std::promise用法


多線程 等待一次性事件 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);
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::ref(pro), 10);
t1.detach();
std::cout << ft1.get() << std::endl;

3,std::promise的拷貝構造函數是被刪除了的,所以std::promise作為函數的參數時,必須用std::ref(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::ref(p), 10);
  t1.detach();

  std::cout << f.get() << std::endl;
  pthread_exit(NULL);
}

github源代碼

c/c++ 學習互助QQ群:877684253

本人微信:xiaoshitou5854


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM