首页 技术 正文
技术 2022年11月18日
0 收藏 921 点赞 4,680 浏览 1324 个字

多线程 等待一次性事件 future概念

背景:有时候,一个线程只等待另一个线程一次,而且需要它等待的线程的返回值。

案例:滴滴叫车时,点完了叫车按钮后,叫车的后台线程就启动了,去通知周围的出租车。这时,用户就可以去干别的了,而且用户只等待叫车的线程一次就够了,也就是有出租车应答了,这个等待就结束了,不会去再次等待有别的出租车应答。应答后,叫车的线程会返回出租车的车牌号,出租车的位置等信息,给叫车的用户。

问题:实现上面的场景,很容易就联想到用多线程去实现,但是std::thread是没有返回值,所以无法得到某个线程的返回值。

std::future解决了这个问题。future是有返回值的,并且只等待某个线程一次。

future用法:在用户叫车时间点,调用std::async方法,启动叫车,叫车成功后,叫车线程通知用户线程,用户线程调用future对象的get()方法,得到出租车的具体信息。

future是模板类,线程方法返回值的类型,就是模板的类型。

代码:

#include <future>
#include <iostream>
#include <unistd.h>int return_from_thread(int val){
std::cout << val << std::endl;
//sleep(1);
return val;
}
void do_something(){
std::cout << "在等滴滴来车" << std::endl;
}int main(){
//std::future<int> ret = std::async(std::launch::deferred,return_from_thread, 10);
//std::future<int> ret = std::async(std::launch::async,return_from_thread, 10);
std::future<int> ret = std::async(return_from_thread, 10);
do_something();
//ret.wait();
std::cout << "车来了,车牌号:" << ret.get() << std::endl;
std::cout << "end" << std::endl;
}

github源代码

编译方法:

g++ -g XXX.cpp -std=c++11 -pthread

运行结果:

在等滴滴来车
车来了,车牌号:10
10
end

知识点:

  • 调用get方法后,当前线程就会被阻塞,知道被等待的线程结束。

std::async第一个参数决定:是开启一个新的线程,还是不开新的线程

  • std::launch::async:开启一个新的线程,执行指定的方法。
  • std::launch::deferred:不开新的线程,直到在future上调用wait()或者get()方法,才会执行指定的方法。
  • std::launch::deferred | std::launch::async:由系统决定是开一个新的线程还是不开。
  • 不指定第一个参数的效果和std::launch::deferred | std::launch::async相同。

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

本人微信:xiaoshitou5854

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:8,999
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,511
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,357
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,140
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,770
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,848