c/c++ 多线程 detach的困惑
程序员文章站
2022-04-15 11:06:38
多线程 detach的困惑 求大神解答: 1,当在一个函数里启动一个线程后,并detach了 2,detach的线程里使用了这个函数里new出来的一个对象 3,detach后,delete了这个对象 4,为什么detach在线程里,使用了在3处delete的内存还不报错误??? c++ includ ......
多线程 detach的困惑
求大神解答:
1,当在一个函数里启动一个线程后,并detach了
2,detach的线程里使用了这个函数里new出来的一个对象
3,detach后,delete了这个对象
4,为什么detach在线程里,使用了在3处delete的内存还不报错误???
#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); thread t(b); //cout << "before join " << *local << endl; delete local; cout << "end delete" << endl; t.detach(); //t.join(); cout << "after join " << *local << endl; cout << "func end" << endl; } int main(){ func(); sleep(10); cout << "end" << endl; }
参数使用指针的引用就报错:
#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 < 10000; ++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); thread t(b); //cout << "before join " << *local << endl; delete local; cout << "end delete" << endl; t.detach(); //t.join(); cout << "after join " << *local << endl; cout << "func end" << endl; } int main(){ func(); sleep(10); cout << "end" << endl; }
c/c++ 学习互助qq群:877684253
本人微信:xiaoshitou5854
上一篇: C语言的合法标识符与整型详解