我运行这段代码
class ttt {
public:
~ttt() {
LOG(INFO);
flush();
}
bool flush() {
//std::lock_guard<boost::fibers::mutex> lock(_mutex);
LOG(INFO);
_mutex.lock();
LOG(INFO);
auto ret = flush_nonlock();
LOG(INFO);
_mutex.unlock();
LOG(INFO);
return ret;
}
private:
bool flush_nonlock() {
LOG(INFO);
return std::rand()%2;
}
boost::fibers::mutex _mutex;
};
int main() {
static ttt t;
std::cout << t.flush() << std::endl;
return 0;
}我得到了
terminate called after throwing an instance of 'boost::fibers::lock_error'
what(): boost fiber: a deadlock is detected: Resource deadlock avoided它打印的最后一个日志在_mutex.lock()之前。如果t不是静态变量,它不会抛出任何错误。如果我在主函数中删除t.flush(),它不会抛出任何错误。像我在笔记中写的那样使用std::lock_guard,它旁边的行不会打印出来。我不明白为什么,我处理过的案件有什么不同。
我的代码是用gcc 5.4.0构建的,有-O0
发布于 2017-07-04 22:39:24
static ttt t;
在boost.fiber的内部数据被析构之后,你在main中的静态ttt实例可能会被析构。从~ttt()访问mutext::lock()中的context::active()可能会返回空指针。
编辑: boost.fiber在内部使用持有活动纤程的线程本地静态(以便能够从深层调用堆栈挂起)。因为ttl被声明为静态的,所以编译器可以任意顺序地析构ttl实例和boost.fiber内部静态。
https://stackoverflow.com/questions/44898650
复制相似问题