[英]C++ boost thread causes segmentation fault when instantiated twice
我有一個類在構造時運行后台任務(參見構造函數)。 然后停止此任務,並在銷毀對象時將線程連接到析構函數中:
// 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;
為什么?
Xcode給出錯誤:
試圖使用已刪除的功能
Foo :: Bar不能使用上面的語法(&Foo :: Bar)調用,因為它不是靜態函數。 它有一個隱藏的參數,導致簽名不匹配。
更多相關內容: 來自類的pthread函數
在初始化程序列表上使用成員函數也是不好的做法,行為未定義。 引用到這里:
可以從成員初始值設定項調用成員函數(包括虛擬成員函數),但如果並非在此時初始化所有直接庫,則行為未定義。
http://en.cppreference.com/w/cpp/language/initializer_list
以下作品:
void bar(atomic_int*exit) {
while (*exit) {
// sleep for 1 minute.
this_thread::sleep_for(std::chrono::seconds(2));
// do other stuff endlessly
}
}
class Foo {
thread theThread;
atomic_int _exit;
public:
// Instantiate background task
Foo(): _exit(1)
{
// do other stuff
init();
}
void init()
{
theThread = std::thread (&bar,&_exit);
}
// Stop background task
~Foo() {
_exit = 0;
theThread.join();
}
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.