多线程 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
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/c-cdevelopment/606685.html