C++关键字之Future promise and async()

主线程将x传递给子线程,子线程将结果x再传递给主线程。

#include <iostream>
#include <future>
#include <thread>
using namespace std;

void myfun(int N,int& x)
{
    int res =1;
    for(int i=N;i>1;i--)
    {
        res *= i;
    }
    cout<<"Result res is:"<<res<<endl;
	x=res;
    
}

int main() {
	
    int x;
	std::thread t1(myfun,4,std::ref(x));
    t1.join();
    cout<<"Result x is:"<<x<<endl;    
	
	return 0;
}

现在x是主线程与子线程的共有资源,因此我们需要来进行保护

#include <iostream>
#include <future>
#include <thread>
using namespace std;
mutex mu;
condition_variable cond;

void myfun(int N,int& x)
{
    int res =1;
    for(int i=N;i>1;i--)
    {
        res *= i;
    }
    cout<<"Result res is:"<<res<<endl;
	x=res;
    
}

int main() {
	
    int x;
	std::thread t1(myfun,4,std::ref(x));
    t1.join();
    cout<<"Result x is:"<<x<<endl;    
	
	return 0;
}

这样就需要调用mu.lock()/mu.unlock()   cond.wait()/cond.notify()非常的麻烦。同时还有两个全局变量需要注意。这样我们的代码结构就会变得混乱。

#include <iostream>
#include <thread>
#include <vector>
#include <future>
using namespace std;
int fun1(std::future<int>& f)
{

   int res =1;
   int N = f.get();
    for(int i=N;i>1;i--)
    {
       res *= i;
    }	
   cout<<"Result res is:"<<res<<endl;
   return res;
}


int main()
{
   int x;
   std::promise<int> p;
   std::future<int> f =p.get_future();
  // future<int> fu = async(fun1,4);

   future<int> fu = async(std::launch::async,fun1,std::ref(f));
   //std::launch::defered,fun1 will be executed in the same thread
   //std::launch::async,fun1 will be executed in another thread
   //std::launch::defered|std::launch::async fun1 will be executed depend on the 
   //do some thing
    std::this_thread::sleep_for(chrono::milliseconds(20));
    p.set_value(4);
     x = fu.get();
   //fu.get();//get only can be called once,or it will be crash
   cout << "Get from child:"<<x<<endl;
   return 0;
}


 

 如果把p.set_value(4);去除会报一个std::future_errc::broken_promise的错误。

 使用set_exception()就可以打破这个promise。会返回To err is human 这个错误。

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

aFakeProgramer

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值