C++11多线程のfuture,promise,package_task

一、c++11中可以在调用进程中获取被调进程中的结果,具体用法如下

// threadTest.cpp: 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
#include <thread>
#include <mutex>
#include <string>
#include <fstream>
#include <deque>
#include <condition_variable>
#include <future>

using namespace std;

int factorial(int n) 
{
    int res = 1;
    for (int i = n; i > 1; i--)
        res *= i;
    return res;
}


int main()
{
    int x;

    std::future<int> fu = std::async(factorial,4);
    x = fu.get();

    cout << "result is " << x << endl;
    std::getchar();
    return 0;
}

二、promise将值传递给子线程

// threadTest.cpp: 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
#include <thread>
#include <mutex>
#include <string>
#include <fstream>
#include <deque>
#include <condition_variable>
#include <future>

using namespace std;

int factorial(future<int> &f) 
{
    int n = f.get();
    int res = 1;
    for (int i = n; i > 1; i--)
        res *= i;
    return res;
}


int main()
{
    int x;
    std::promise<int> p;
    std::future<int> f = p.get_future();

    std::future<int> fu = std::async(std::launch::async ,factorial, std::ref(f));
    p.set_value(4);
    x = fu.get();

    cout << "result is " << x << endl;
    std::getchar();
    return 0;
}

有promise的情况下必须有setvalue;promise和future均不能被复制,只能被移动。

 

如果我们需要多个子线程执行一段代码,那么可以使用std::shared_future()来创建sf,来获取一个变量。

三、可调用对象

// threadTest.cpp: 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
#include <thread>
#include <mutex>
#include <string>
#include <fstream>
#include <deque>
#include <condition_variable>
#include <future>

using namespace std;

class A
{
public:
    void f( int a,char c) {}
    int operator()(int n) { return 0; }


private:

};

void foo(int x) {}


int main()
{
    A a;

    std::thread t1(a, 6);         //传递a的copy给子线程
    std::thread t2(std::ref(a),6);//传递a的引用给子线程
    std::thread t3(std::move(a),6);//a在主线程已经失效
    std::thread t4(A(), 6);        //传递临时创建的对象给子线程

    std::thread t5(foo,6);          //传递一个函数给
    std::thread t6([](int x) {}, 6);  //传递一个lambd给子线程
    std::thread t7(&A::f,a,8,"w");    //传递a的copy的成员函数给子线程
    std::thread t7(&A::f, &a, 8, "w");

    std::getchar();
    return 0;
}

四、package_task异步访问可调用对象的结果

 

转载于:https://www.cnblogs.com/xietianjiao/p/6181758.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值