线程之间共享数据

#include <iostream>       // std::cin, std::cout, std::ios
#include <functional>     // std::ref
#include <thread>         // std::thread
#include <future>         // std::promise, std::future
#include <exception>      // std::exception, std::current_exception

void task(std::promise<int>& prom)
{
    int x = 0;
    /*
     * 这里一般一个非常耗时耗cpu的操作如查找,计算等,在此过程中得到x的最终值,这里我们直接赋值为10
     */
    x = 10;

    //设置共享状态的值,同时promise会设置为ready
    prom.set_value(10);         
}

void print_int(std::future<int>& fut) 
{
    //如果共享状态没有设置ready,调用get会阻塞当前线程
    int x = fut.get();          
    std::cout << "value: " << x << '\n';
}

int main ()
{
    // 生成一个 std::promise<int> 对象.
    std::promise<int> prom;

    // 和 future 关联.
    std::future<int> fut = prom.get_future();         
    
    // 将 prom交给另外一个线程t1 注:std::ref,promise对象禁止拷贝构造,以引用方式传递
    std::thread th1(task, std::ref(prom));            
    
    // 将 future 交给另外一个线程t.
    std::thread th2(print_int, std::ref(fut));        
    
    /*
     *主线程这里我们可以继续做一大堆我们想做的事,不用等待耗时的task线程,也不会因为等待task的执行结果而阻塞
     */
    
    th1.join();
    th2.join();
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值