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 }