zoukankan      html  css  js  c++  java
  • 35.并行计算获取结果

     1 #define _CRT_SECURE_NO_WARNINGS
     2 #include <iostream>
     3 #include <thread> 
     4 #include <future>//线程将来的结果
     5 #include <chrono>
     6 #include <mutex>
     7 using namespace std;
     8 
     9 mutex g_m;
    10 
    11 
    12 void main()
    13 {
    14     auto run = [=](int index) 
    15     {
    16         lock_guard<mutex> lckg(g_m);
    17         //获取线程id以及参数
    18         cout << this_thread::get_id << " " << index << endl;
    19         //等待1秒
    20         this_thread::sleep_for(chrono::seconds(1));
    21         return index * 1024;//返回结果
    22     };
    23     //创建两任务包,用于初始化线程
    24     packaged_task<int(int)> pt1(run);
    25     packaged_task<int(int)> pt2(run);
    26 
    27     //开启线程
    28     thread t1([&]() {pt1(2); });
    29     thread t2([&]() {pt2(3); });
    30     cout << pt1.get_future().get() << endl;
    31     cout << pt2.get_future().get() << endl;
    32     t1.join();
    33     t2.join();
    34     cin.get();
    35 }
  • 相关阅读:
    Web的攻击技术
    基于HTTP的功能追加协议
    确认访问用户身份的认证
    基本数据结构的模拟
    BFS与DFS
    KMP算法
    Trie字典树
    C++的结构体使用
    C++入门(命名空间)
    算法:C++入门
  • 原文地址:https://www.cnblogs.com/xiaochi/p/8549181.html
Copyright © 2011-2022 走看看