【问题标题】:std::thread not working on linux eclipsestd::thread 在 linux eclipse 上不起作用
【发布时间】:2013-12-25 14:43:43
【问题描述】:

我不知道为什么,但是在 eclipse 中将 c++11 包含到我的项目中并使用 std::array 等新功能后,当我使用 std::thread 时它突然无法工作。

这是我正在尝试运行的示例:

#include <iostream>
#include <string>
#include <thread>

void print_message_function(const std::string& msg);

int main()
{
    std::string message1 = "Thread 1";
    std::string message2 = "Thread 2";

    std::thread thread1(print_message_function, message1);
    std::thread thread2(print_message_function, message2);

    thread1.join();
    thread2.join();
}

void print_message_function(const std::string& msg)
{
    std::cout << msg << std::endl;
}

编译时没有错误,运行时也没有错误(也没有输出..),但是使用调试工具时它在这一行崩溃:

std::thread thread1(print_message_function, message1);

这是崩溃时的堆栈:

Thread [1] (Suspended: Signal 'SIGSEGV' received. Description: Segmentation fault.) 
    5 _dl_fixup()  0x0000003d6920df7c   
    4 _dl_runtime_resolve()  0x0000003d69214625 
    3 std::thread::_M_start_thread()  0x0000003d762b65a7    
    2 std::thread::thread<void (&)(std::string const&), std::string&>() /usr/include/c++/4.4.4/thread:133 0x0000000000402268    
    1 main() /.../Main.cpp:12 0x0000000000401e8d    

为什么会这样?

【问题讨论】:

  • 你链接到-pthread了吗?
  • Thread 封装了原生线程库,在 linux 上是 pthreads。不确定 eclipse 如何处理编译选项,但在编译/链接命令末尾添加 -pthread
  • 在这里找到了一个教程:blog.asteriosk.gr/2009/02/15/… 现在一切正常,谢谢,发布一个答案,这样问题就不会永远保持开放。

标签: c++ linux eclipse multithreading c++11


【解决方案1】:

您需要在编译命令中使用 -pthread 链接 pthreads 库。

【讨论】:

  • 注意,-pthread 不仅仅用于链接(否则可以简单地使用-lpthread。有关更多信息,请参阅this SO question
猜你喜欢
  • 1970-01-01
  • 2021-09-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-07
  • 1970-01-01
相关资源
最近更新 更多