码迷,mamicode.com
首页 > 编程语言 > 详细

线程 packaged_task future

时间:2016-09-10 11:38:04      阅读:161      评论:0      收藏:0      [点我收藏+]

标签:

http://www.cnblogs.com/haippy/p/3279565.html


#include <iostream> // std::cout #include <future> // std::packaged_task, std::future #include <chrono> // std::chrono::seconds #include <thread> // std::thread, std::this_thread::sleep_for // count down taking a second for each value: int countdown (int from, int to) { for (int i=from; i!=to; --i) { std::cout << i << \n; std::this_thread::sleep_for(std::chrono::seconds(1)); } std::cout << "Finished!\n"; return from - to; } int main () { std::packaged_task<int(int,int)> task(countdown); // 设置 packaged_task std::future<int> ret = task.get_future(); // 获得与 packaged_task 共享状态相关联的 future 对象. std::thread th(std::move(task), 10, 0); //创建一个新线程完成计数任务. int value = ret.get(); // 等待任务完成并获取结果. std::cout << "The countdown lasted for " << value << " seconds.\n"; th.join(); return 0; }

 

 

 

#include <iostream>     // std::cout
#include <utility>      // std::move
#include <future>       // std::packaged_task, std::future
#include <thread>       // std::thread

int main ()
{
    std::packaged_task<int(int)> foo; // 默认构造函数.

    // 使用 lambda 表达式初始化一个 packaged_task 对象.
    std::packaged_task<int(int)> bar([](int x){return x*2;});

    foo = std::move(bar); // move-赋值操作,也是 C++11 中的新特性.

    // 获取与 packaged_task 共享状态相关联的 future 对象.
    std::future<int> ret = foo.get_future();

    std::thread(std::move(foo), 10).detach(); // 产生线程,调用被包装的任务.

    int value = ret.get(); // 等待任务完成并获取结果.
    std::cout << "The double of 10 is " << value << ".\n";

return 0;
}

 

packaged_task 主要是包装一下函数,相当与函数指针,

直接就能够被线程调用。

它同时提供了一个同步的机制, .get_future()方法。

定义的future变量如 std::future<int>fut = tsk.getfuture();

通过fut.get()获得同步,也就是说,要等待执行结束,才执行下面的代码。 同时可以获得线程函数的返回值。

 

#include <iostream>     // std::cout
#include <utility>      // std::move
#include <future>       // std::packaged_task, std::future
#include <thread>       // std::thread

// a simple task:
int triple(int x) { return x * 3; }

int main()
{
    std::packaged_task<int(int)> tsk(triple); // package task


    std::future<int> fut = tsk.get_future();
    std::thread(std::ref(tsk), 100).detach();
    std::cout << "The triple of 100 is " << fut.get() << ".\n";


    // re-use same task object:
    tsk.reset();
    fut = tsk.get_future();
    std::thread(std::move(tsk), 200).detach();
    std::cout << "Thre triple of 200 is " << fut.get() << ".\n";

    return 0;
}

 

线程 packaged_task future

标签:

原文地址:http://www.cnblogs.com/yuguangyuan/p/5858945.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!