![](/img/trans.png)
[英]C++ std::thread terminate called without an active exception Aborted
[英]wxWidgets - terminate called without an active exception (using std::thread)
我正在編寫GUI應用程序,它使用我自己的基於C ++ 11標准庫boost::asio
的庫。 這是從wxApp
派生的gui_client
類的gui_client::OnInit
和gui_client::OnExit
方法的gui_client
:
bool gui_client::OnInit()
{
io_service_ = new boost::asio::io_service;
client_ = new client(*io_service_);
frame = new main_frame();
std::thread reader([this]() {
// thread code
});
reader_thread = &reader;
frame->Show();
Debug("Returning OnInit");
return true;
}
int gui_client::OnExit()
{
reader_thread->join();
return 0;
}
一切都會編譯並開始應用程序。 我在命令行中看到調試信息(“ Returning OnInit”),然后:
在沒有活動異常的情況下終止調用
我試圖在某些wxApp
函數的gdb
設置斷點,但是找不到返回錯誤的位置。 gui_client
類只有三種方法:
virtual bool OnInit()
virtual int OnExit()
client * get_client()
當我不啟動讀取器線程( std::thread reader
)時,一切工作正常。 當我在lambda函數中使用空循環啟動線程時,出現了上面提到的錯誤。 我還確定線程代碼正確,因為相同的代碼在CLI測試應用程序中效果很好。
我使用wxWidgets 3.0.1.0
和g++ 4.7.2
(Debian)。 我使用以下g ++命令進行編譯:
g++ `wx-config --version=3.0 --cxxflags` -std=c++11 -I./headers -I../headers -L../lib/Debug -DDEBUG -g -c -o [obj_file] [source]
和此命令鏈接:
g++ `wx-config --version=3.0 --cxxflags` -std=c++11 -I./headers -I../headers -L../lib/Debug -DDEBUG -g [obj_files] -ltamandua `wx-config --version=3.0 --libs` -lboost_system -pthread -o [output]
問題在這里:
std::thread reader([this]() {
// thread code
});
reader_thread = &reader;
在OnInit
函數結束后, reader
將被銷毀(並且將終止,因為thread
是可連接的,所以將被調用)。 在這種情況下,您應該在類中使用智能指針,或者使用new
創建reader_thread
,或者只是簡單地將線程保存在對象中,然后通過移動將其分配給您的reader_thread
(reader_thread應該是對象,而不是指針)。
1) reader_thread = std::make_shared<std::thread>([this]() {});
2) reader_thread = new std::thread([this]() {});
3)
std::thread reader([this](){});
reader_thread = std::move(reader);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.