运行时错误消息 std::system_error - 操作不允许的原因是什么,包括多线程?

60

2022年更新

C++ 17和20现在在标准库中内置了对多线程的支持。我建议使用这些而不是使用Linux特定的pthread库。

原始问题

我在64位kubuntu linux,版本13.04上编写了一个测试线程的程序。实际上,我从别人编写测试程序的代码中抄袭了这个程序。

#include <cstdlib>
#include <iostream>
#include <thread>

void task1(const std::string msg)
{
    std::cout << "task1 says: " << msg << std::endl;
}

int main(int argc, char **argv)
{
    std::thread t1(task1, "Hello");
    t1.join();

    return EXIT_SUCCESS;
}

我使用以下方式进行编译:

g++ -pthread -std=c++11 -c main.cpp
g++ main.o -o main.out

接着跑:

./main.out
作为旁注,在我使用'ls -l'命令时,main.out以绿色文本显示,就像所有可执行文件一样,并且在其名称末尾还有一个星号。这是为什么?
回到手头的问题:当我运行main.out时,出现了一个错误,错误信息如下:
terminate called after throwing an instance of 'std::system_error'
  what():  Operation not permitted
Aborted (core dumped)

有人有解决这个问题的想法吗?


这个问题不应该被标记为重复。还有其他情况会导致出现这个错误信息,不仅限于线程链接问题。 - Kemin Zhou
1个回答

109

你没有正确地链接pthread库,请尝试以下命令(注意:顺序很重要)

g++  main.cpp -o main.out -pthread -std=c++11

或者

只需两个命令即可完成

g++ -c main.cpp -pthread -std=c++11         // generate target object file
g++ main.o -o main.out -pthread -std=c++11  // link to target binary

11
你可以使用两个命令来完成。但是在编译和链接时都必须指定“-pthread”。 - David Schwartz
6
@billz,您能否详细说明为什么-pthread的顺序很重要? - hetepeperfan
2
GCC 手册中的 -pthread 选项明确说明:“此选项为预处理器和链接器设置标志。” 在编译和链接时都应使用它。 - Jonathan Wakely
@JonathanWakely 感谢您对此进行审查。这对我来说也是新的。我已经更新了我的答案。 - billz
在某个其他论坛上有人说,在末尾加上-Wl,--no-as-needed可以解决错误,因为在g++ 4.8中存在一些bug。 - Vivek Kumar
显示剩余6条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接