[英]Starting a std::thread with static linking causes segmentation fault
要學習c ++ 11(和boost)我正在使用boost asio和c ++ 11(用於線程和lambdas)編寫一個簡單的http服務器。
我想測試新的c ++ 11 lambdas和std :: thread,所以我嘗試在帶有lambda的std :: thread中啟動這樣的io_service.run()
:
#include <iostream>
#include <thread>
#include <boost/asio.hpp>
#include <boost/thread.hpp>
using std::cout;
using std::endl;
using boost::asio::ip::tcp;
class HttpServer
{
public:
HttpServer(std::size_t thread_pool_size)
: io_service_(),
endpoint_(boost::asio::ip::tcp::v4(), 8000),
acceptor_(io_service_, endpoint_)
{ }
void Start() {
acceptor_.listen();
cout << "Adr before " << &io_service_ << endl;
std::thread io_thread([this](){
cout << "Adr inside " << &io_service_ << endl;
io_service_.run();
});
io_thread.join();
}
private:
boost::asio::io_service io_service_;
tcp::endpoint endpoint_;
tcp::acceptor acceptor_;
};
int main() {
HttpServer server(2);
server.Start();
}
這終止於分段錯誤。 另外,有時候它會在lambda中運行cout,有時候不會(盡管endl應該刷新)。 無論如何,它會輸出正確的io_service_
地址。 但是,當我用boost::thread
替換std::thread
(沒有其他更改!)時,一切正常。
如果有人知道導致問題的原因(可能是asio,std :: thread或std :: lambda),我將不勝感激。
附加信息:
根據另一個帖子訪問成員io_service_在一個lambda中捕獲this
是正常的,就像我這樣做。
我在Ubuntu上運行gcc 4.6.1並提升1.46。 G ++參數:
g++ -std=c++0x -static -I/home/andre/DEV/boost_1_48_0/include/ -L/home/andre/DEV/boost_1_48_0/lib/ -o webserver main.cpp -lboost_system -lboost_thread -lpthread
更新:
刪除-static修復了問題。 我發現問題與boost或lambdas無關,並且可以在構建靜態和使用std::thread
時重現。 出於任何原因,這種組合不起作用。 我認為這篇文章描述的幾乎相同,但我並不真正理解細節,錯誤信息也不同。
所以我想知道為什么std::thread
和靜態鏈接似乎不能一起工作。 這里有不允許靜態鏈接的原因嗎? 我更新了問題標題並刪除了升級標記。
將您的應用程序與-Wl,--whole-archive -lpthread -Wl,--no-whole-archive
鏈接-Wl,--whole-archive -lpthread -Wl,--no-whole-archive
更多信息,請訪問https://gcc.gnu.org/bugzilla/show_bug.cgi?id=52590這對我有用。
刪除-static解決了這個問題。 我發現它與boost或lambdas沒有任何關系,但是使用靜態鏈接和std::thread
,它們似乎並沒有因為任何未知原因而一起工作(另請參閱這篇可能相關的帖子 )。
我猜他們為什么不能一起工作的問題 - 雖然很有趣 - 現在已超出范圍,我很高興答案,所以這可以標記為已回答。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.