1 #include <iostream>
2 #include<thread>
3 #include <ctime>
4 #include<chrono>
5
6 using namespace std;
7
8 #define NAME_LINE 40
9
10
11 volatile clock_t startt, endt;
12
13 void prt() {
14 cout << "cout"<<endl;
15 };
16
17 void f1(int n) {
18 for (int i = 0; i < n; ++i) {
19 std::cout << "Thread " << n << " executing\n";
20 std::this_thread::sleep_for(std:: chrono::milliseconds(10));
21 prt();
22 }
23 }
24
25 void f2(int& n) {
26 for (int i = 0; i < 5; ++i) {
27 std::cout << "Thread 2 executing\n";
28 ++n;
29 std::this_thread::sleep_for(std::chrono::milliseconds(10));
30 prt();
31 }
32 }
33
34
35 void thread_task(int n) {
36 std::this_thread::sleep_for(std::chrono::seconds(n));
37 std::cout << "hello thread "
38 << std::this_thread::get_id()
39 << " paused " << n << " seconds" << std::endl;
40
41 }
42
43 int main()
44 {
45 //experiment 1
46 int n = 0;
47 std::thread t1; // t1不再是线程
48 std::thread t2(f1, n+1); //
49 std::thread t3(f2, std::ref(n)); //
50 std::thread t4(std::move(t3)); //t4现在在跑f2(),t3不再是线程了
51
52 t2.join(); // 主线程阻塞,直到线程t2跑完它的传入函数
53 t4.join();
54 cout << "final value of n is:" << n << endl;
55
56
57 // experiment 2
58 std::thread threads[5];
59 std::cout << "Spawning 5 threads...\n";
60 for (int i = 0; i < 5; ++i) {
61 threads[i] = std::thread(thread_task,i+1);
62 }
63 std::cout << "Done of spawning threads! Now wait for them to join \n";
64 for (auto& t : threads) {
65 t.join();
66 }
67 std::cout << "All threads joined.\n";
68
69 return EXIT_SUCCESS;
70 }
C++11 并发指南二(std::thread 详解) - Haippy - 博客园 (cnblogs.com)