【发布时间】:2016-03-03 01:24:23
【问题描述】:
以下程序崩溃。但我真的不明白为什么。布尔值 my_shared_resouce 在现实生活中是一个异步队列,最终通过消息传递停止线程内部的循环。
但是,以下程序崩溃,因为析构函数似乎被多次调用。第一次这样做是在 main() 中的睡眠结束之前很久。如果我删除 delete my_shared_resource; 我可以看到析构函数被调用了三遍......
但是,按照我目前的理解,只有在 main() 完成时才应该调用析构函数。
#include <thread>
#include <chrono>
#include <iostream>
using namespace std;
class ThreadedClass {
public:
ThreadedClass() {
my_shared_resource = new bool(true);
}
virtual ~ThreadedClass() {
delete my_shared_resource;
cout << "destructor" << endl;
}
void operator()(){
loop();
}
void stop() {
*my_shared_resource = false;
}
private:
void loop() {
while (*my_shared_resource) {
// do some work
this_thread::sleep_for(std::chrono::milliseconds(1000));
}
}
bool* my_shared_resource;
};
int main(int argc, char** argv) {
ThreadedClass instance;
std::thread t(instance);
this_thread::sleep_for(std::chrono::milliseconds(1000));
cout << "Did some work in main thread." << endl;
instance.stop();
t.join();
return 0;
}
用g++编译(Ubuntu 4.8.4-2ubuntu1~14.04)4.8.4
编译为 g++ --std=c++0x thread.cpp -pthread
谁能告诉我这个设计有什么问题。
【问题讨论】:
-
你有一个数据竞赛,顺便说一句。使用
std::atomic<bool>。
标签: c++ multithreading c++11