多線程 detach的困惑
求大神解答:
1,當在一個函數里啟動一個線程后,並detach了
2,detach的線程里使用了這個函數里new出來的一個對象
3,detach后,delete了這個對象
4,為什么detach在線程里,使用了在3處delete的內存還不報錯誤???
-----start 更新分割線2018/10/27 上午-------------
回答4的問題:
線程還沒來得及執行,main函數就執行完了,直接殺死還沒有執行完的線程,所以線程里使用了已經delete的內存,也沒有出錯。如果在main函數里調用sleep(2),就會出錯誤。
如果當main函數結束后,還不想結束其他由main函數創建的子線程,就必須調用下pthread_exit(NULL)。
#include <iostream>
#include <thread>
#include <unistd.h>
using namespace std;
class bad{
public:
bad(int* i) : data(i){
cout << "addr2:" << data << endl;
}
void operator()(){
for(unsigned j = 0; j < 10000000000; ++j){
something(data);
}
}
private:
void something(int* i){
*i = 100;
cout << *i << endl;
};
int* data;
};
void func(){
int* local = new int(10);
cout << "addr1:" << local << endl;
bad b(local);
delete local;
thread t(b);
//cout << "before join " << *local << endl;
cout << "end delete" << endl;
t.detach();
//t.join();
cout << "after join " << *local << endl;
cout << "func end" << endl;
}
int main(){
func();
pthread_exit(NULL);
cout << "end" << endl;
}