zoukankan      html  css  js  c++  java
  • 2.任务包多线程并行计算

     1 #include <future>//进程通信,获取未来的结果
     2 #include<iostream>
     3 #include <thread>
     4 #include <string>
     5 #include <chrono>//时间
     6 #include <mutex>//互斥量
     7 using namespace std;
     8 
     9 //创建互斥量
    10 mutex m;
    11 
    12 //全局通信变量
    13 promise<string> val;
    14 
    15 void main()
    16 {
    17     //访问外部变量[=]
    18     auto fun = [=](int index)->int
    19     {
    20         //加锁
    21         lock_guard<mutex> lckg(m);
    22 
    23         //显示线程id
    24         cout << "线程编号:" << this_thread::get_id() << "  " << index << endl;
    25         //等待十秒
    26         this_thread::sleep_for(chrono::seconds(1));
    27 
    28         //计算
    29         return index * 1024;
    30     };
    31 
    32     //获取返回值,创建任务包
    33     packaged_task<int(int)> pt1(fun);
    34     packaged_task<int(int)> pt2(fun);
    35 
    36     thread t1([&]() 
    37     {
    38         pt1(23); 
    39     });
    40     thread t2([&]()
    41     {
    42         pt2(26);
    43     });
    44 
    45     //开启线程,获取结果,只能获取一次
    46     int res1 = pt1.get_future().get();
    47     int res2 = pt2.get_future().get();
    48     int last = res1 + res2;
    49     cout << last << endl;
    50 
    51     t1.joinable();
    52     t2.joinable();
    53     t1.join();
    54     t2.join();
    55     system("pause");
    56 }
  • 相关阅读:
    ShellExecuteEx 函数说明
    npm
    Byte和char
    如何高效阅读一个项目
    C++中慎用malloc
    #ifdef
    string
    C++与C混合编译
    git@github.com: Permission denied (publickey).
    connect to host github.com port 22: Connection refused
  • 原文地址:https://www.cnblogs.com/xiaochi/p/8689058.html
Copyright © 2011-2022 走看看