Third, the thread mass participation, detach pit, member functions do thread function

First, the temporary object passed as a parameter thread

Each thread to give him a number, different numbers do different tasks.

1, 1 trap

 1 #include <iostream>
 2 #include <thread> //线程
 3 using namespace std;
 4 
 5 void prt(const int &i,char *buf){
 6     cout << i<<endl;
 7     cout << buf << endl;
 8 }
 9 int main(){
10     int& a=1;
11     int& b=a;
12     char mybuf[]="this is a test";
13     myObj Thread (PRT, A, mybuf); // The first parameter is the name of the function thread, the next parameter is a function of the thread 
14      myobj.detach ();
 15      COUT << " main End " << endl;
 16      return  0 ;
 17 }

There above the thread function code is a reference to the parameter i. Create a child thread in 12 lines of code is the argument passed it cited a, so the thread function i first should be the same one a address.

If the main thread to perform finished, it was a release, that time i visit the child thread, and whether to be wrong?

The answer is no, although the child thread is created i is a reference, but in fact, a thread is created, a copy to the thread myobj, references are not really apply here, but the copy, not when referencing effective. So i can still access the quilt thread, because a copy of a copy to i, i to a different address.

But for mybuf the string, it is unsafe. Because buf is a pointer, the content is a pointer memory address, even if it is copied, it points to the memory address of the contents copied again only when the main thread of execution is over, the address at the memory has been released, it is not accessible to be wrong!

How to pass a string that it? ? ? ? Look Trap II

2, Trap 2

 

3, thread id

4, the timing of the arrest temporary object construction

Third, the transfer class object as a thread smart pointer parameter

Fourth, the member function pointer parameters do thread

Guess you like

Origin www.cnblogs.com/pacino12134/p/11228024.html