线程之间共享数据

来源:互联网 发布:淘宝停留时间怎么看 编辑:程序博客网 时间:2024/05/17 22:26
#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_exceptionvoid 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;}