c/c++语言开发共享c/c++ 多线程 等待一次性事件 std::promise用法

多线程 等待一次性事件 std::promise用法 背景:不是很明白,不知道为了解决什么业务场景,感觉std::async可以优雅的搞定一切的一次等待性事件,为什么还有个std::promise。 用法:和std::async一样,也能够返回std::future,通过调用get_future方法 …


多线程 等待一次性事件 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); }

c/c++ 学习互助qq群:877684253

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

本人微信:xiaoshitou5854

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/c-cdevelopment/606191.html

(0)
上一篇 2021年5月13日
下一篇 2021年5月13日

精彩推荐