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异步访问可调用对象的结果

 

posted @ 2016-12-15 01:11  卖雨伞的小男孩  阅读(971)  评论(0编辑  收藏  举报