线程无法处理错误:启用多线程以使用std :: thread:不允许操作

use*_*158 31 c++ multithreading

我在我的系统上创建并执行了一个简单的线程.当我执行这个程序时,我有错误消息:启用多线程使用std :: thread:不允许操作

关于我的系统的一些细节:

  • linux ubuntu 13.10
  • g ++ 4.8.1

我编译包括库的源代码 pthread

源代码:

#include <iostream>
#include <thread>


using namespace std;

void func(void) {
  cout << "test thread" << endl;
}


int main() {
  cout << "start" << endl;
  thread t1 (func);

  t1.join();

  cout << "end" << endl;

  return 0;
}
Run Code Online (Sandbox Code Playgroud)

Igo*_*pov 31

您似乎正在尝试使用C++ 11线程.如果是真的那么

  1. 正确的#include <thread>#include <iostream>,即不使用"这些行,并增加#在他们面前.
  2. 编译用g++ -std=c++11 q.cpp -lpthread(依赖命令对较新的g ++有用)

提示:当您在静态链接库中使用线程并在可执行文件中使用此库时,您必须将该标志添加-pthread到可执行文件的link命令.例:

g++ Obj1.o Obj2.o MyStaticLib.a -o MyExecutable -pthread
Run Code Online (Sandbox Code Playgroud)

  • 更清楚一点:问题在于缺少gcc的__- pthread__标志.如果它是`#include`s,那么代码就不会被编译. (10认同)
  • 为什么需要 -pthreads?非 C++11 代码中也需要这样做吗? (2认同)