【发布时间】:2017-05-04 15:08:47
【问题描述】:
我有一个在构造时运行后台任务的类(请参阅构造函数)。然后停止此任务,并在对象被销毁时将线程加入析构函数中:
// Foo.hpp -------------------------------
#include <boost/thread.hpp>
#include <boost/date_time/posix_time.hpp>
class Foo {
boost::thread theThread;
Foo();
~Foo();
void bar() const;
}
// Foo.cpp -------------------------------
// This is the background task.
void Foo::bar() const {
while (true) {
try {
// sleep for 1 minute.
boost:this_thread_sleep(boost::posix_time::minutes(1));
// do other stuff endlessly
}
// boost interrupt was called, stop the main loop.
catch (const boost::thread_interrupted&)
{
break;
}
}
// Instantiate background task
Foo::Foo()
: theThread(&Foo::bar, this)
{
// do other stuff
}
// Stop background task
Foo::~Foo() {
theThread.interrupt()
theThread.join();
}
现在,当我有一个类的单个实例时,这可以正常工作:
// main.cpp
Foo f;
// do other stuff with f
但是当我这样做时,我得到一个分段错误和一个中止的消息:
// main.cpp
Foo *f;
f = new Foo(); // causes seg fault
delete f;
为什么?
【问题讨论】:
-
boost::thread是否尝试取消引用其构造函数中的第二个参数(在您的情况下为this)?如果是这样,那么在初始化列表中使用this作为参数似乎并不安全。 -
不确定是否在将 foo::bar 提供给线程时构建了它
-
抱歉,您的代码无法编译,并且您的析构函数是私有的,因此您无法在 main.cpp 中实例化此类。您确定此代码重现了您的问题吗?
标签: c++ multithreading boost