小编IDO*_*IDO的帖子

多线程段故障析构函数

我在调用函数unit_thread_data\xef\xbc\x8c时出现段错误,实际上它是由~Data()引起的。thread1没问题,但是thread2导致了段错误,整个代码如下:(请原谅糟糕的代码风格),错误信息是双重释放或损坏。其他信息:gcc5.4.0、centos7。有什么帮助吗?非常感谢!

\n
#include <iostream>\n#include <pthread.h>\n#include <unistd.h>\nusing namespace std;\nclass Data\n{\npublic:\n    int* A_;\n    Data()\n    {\n        cout<<"111\\n";\n        A_=NULL;\n    }\n    ~Data()\n    {\n        cout<<"222\\n";\n        if(A_) {\n            delete A_;\n        }\n    }\n};\n\nstruct thread_data_t\n{\n    Data* d;\n};\n\nvoid* _add(void* _pthread_data)\n{\n    thread_data_t* pthread_data = (thread_data_t*) _pthread_data;\n    pthread_data->d->A_ = new int[2];\n    pthread_data->d->A_[0] = 1;\n    pthread_data->d->A_[1] = 2;\n    std::cout<<pthread_data->d->A_[0]+pthread_data->d->A_[1]<<endl;\n    return (void*)0;\n}\n\nvoid unit_thread_data(thread_data_t* pthread_data)\n{\n    for(int i=0;i<2;i++)\n    {\n        delete[] pthread_data[i].d->A_;\n        delete pthread_data[i].d;\n    }\n    delete[] pthread_data;\n}\nint main()\n{\n    int num_threads = 2;\n    pthread_t threads[num_threads];\n    thread_data_t* pthread_data = new thread_data_t[num_threads];\n    for(int i=0;i<num_threads; i++)\n    {\n        pthread_data[i].d = new Data();\n …
Run Code Online (Sandbox Code Playgroud)

c++ destructor pthreads segment

2
推荐指数
1
解决办法
88
查看次数

标签 统计

c++ ×1

destructor ×1

pthreads ×1

segment ×1