這裡,隻是記錄自己的學習筆記。
順便和大家分享多線程的基礎知識。然後從入門到實戰。有代碼。
知識點來源:
https://edu.51cto.com/course/26869.html
C++11 線程建立的多種方式和參數傳遞
1 #include <iostream>
2 #include <thread>
3 #include<string>
4 using namespace std;
5 // Linx -lpthread
6
7
8 class Para {
9 public:
10 Para() { cout << "Create Para " << endl; }
11 Para(const Para& pa) {
12 cout << "copy Para" << endl;
13 }
14 ~Para() { cout << "Drop Para" << endl; }
15 string name;
16 };
17
18
19 //調用回調函數的時候,會再通路一次。。。這裡又進行了一次 拷貝構造
20 void ThreadMian(int p1, float p2, string str , Para pa) {
21 this_thread::sleep_for(1000ms);
22 cout << "ThreadMian p1:" << p1 << ",p2:" << p2 << ",str:" << str <<",pa:"<<pa.name<< endl;
23 }
24
25 int main(int argc,char* argv[]) {
26
27 // th 在建立的時候,對所有傳入的參數都做了一次拷貝
28 //float f1 = 12.1f;
29 //thread th(ThreadMian, 103, f1, "test string para");
30 //th.join();
31
32 thread th;
33 {
34 float f1 = 12.1f;
35 Para pa; //// 建立對象,會預設構造一個對象。。。
36 pa.name = "test Para classs";
37
38
39 //所有的參數做複制
40 th = thread(ThreadMian, 1001, f1, "test para2",pa);//pa傳遞進去之後,thread的構造函數會把參數存一次,這裡會進行一次拷貝構造。
41
42 //類 Para 析構了3次。是走的拷貝構造函數。。
43 }
44
45 th.join();
46
47 return 0;
48 }
總結:
th(線程對象) 在建立的時候,對所有傳入的參數都做了一次拷貝
作者:小烏龜
出處:http://www.cnblogs.com/music-liang/
【轉載請注明出處,歡迎轉載】 希望這篇文章能幫到你