c/c++ 多線程 detach的困惑


多線程 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;
}

c/c++ 學習互助QQ群:877684253

本人微信:xiaoshitou5854


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM