这里,只是记录自己的学习笔记。
顺便和大家分享多线程的基础知识。然后从入门到实战。有代码。
知识点来源:
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/
【转载请注明出处,欢迎转载】 希望这篇文章能帮到你