c/c++ 多线程 detach的困惑
程序员文章站
2022-07-24 12:09:35
多线程 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
下一篇: 买了几瓶2锅头