1. 如果要main thread使用detach方法,尽量不传递引用,一定不能传递指针。
#include <iostream>
using namespace std;
#include "thread"
#include <unistd.h>
//此时ref虽然是引用,却是值传递,因此即使main thread用的detach并且回收了变量ref内存,不会影响thread里ref的值
//此时pointer是地址传递m,因此如果如果main thread 提前退出,会将pointer内存释放出现问题。
void testLocalRef(const int& ref, int * pointer)
{
cout << "The ref's address in other thread is " << &ref << '\n';
cout << "The pointer's address in other thread is " << pointer << '\n';
}
int main(int argc, const char * argv[]) {
// insert code here...
int ref = 1;
int pointer[10] = {1,2,3,4,5};
thread mythread (testLocalRef, ref, pointer);
if(mythread.joinable())
{
mythread.detach();
}
sleep(2);
cout << "The ref's address in main thread is " << &ref << '\n';
cout << "The pointer's address in main thread is " << pointer << '\n';
return 0;
}
结果:
以上结果可以看出,引用在子线程中会作为值传递,两者地址不一样,因此如果主线程提前退出并释放ref内存,不会影响到