用 g + + 编译多线程代码

我有最简单的代码:

#include <iostream>
#include <thread>


void worker()
{
std::cout << "another thread";
}


int main()
{
std::thread t(worker);
std::cout << "main thread" << std::endl;
t.join();
return 0;
}

尽管我仍然不能用 g++编译它来运行。

更多细节:

$ g++ --version
g++ (Ubuntu/Linaro 4.8.1-10ubuntu8) 4.8.1
Copyright (C) 2013 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

编译命令:

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

跑步:

$ ./main.out
terminate called after throwing an instance of 'std::system_error'
what():  Enable multithreading to use std::thread: Operation not permitted
Aborted (core dumped)

现在我被困住了。在互联网上的每一个相关的线程,建议添加 -pthread,而我已经有了它。

我做错了什么?

PS: 这是一个全新的 ubuntu 13.10安装,只安装了 g++软件包和像 chromium这样的小东西

附注:

$ ldd ./a.out
linux-vdso.so.1 => (0x00007fff29fc1000)
libstdc++.so.6 => /usr/lib/x86_64-linux-gnu/libstdc++.so.6 (0x00007fb85397d000)
libgcc_s.so.1 => /lib/x86_64-linux-gnu/libgcc_s.so.1 (0x00007fb853767000)
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007fb85339e000)
libm.so.6 => /lib/x86_64-linux-gnu/libm.so.6 (0x00007fb85309a000)
/lib64/ld-linux-x86-64.so.2 (0x00007fb853c96000)

PPPS: 使用 clang++(v3.2) ,它可以很好地编译和运行

伙计们,这不是 在 Linux 下 GCC 中使用 std: : thread 的正确链接选项是什么?的复制品

PPPPPS:

$ dpkg --get-selections | grep 'libc.*dev'
libc-dev-bin                    install
libc6-dev:amd64                 install
libclang-common-dev             install
linux-libc-dev:amd64                install
98317 次浏览

The answer was provided by a kind member of SO C++ chat.

It looks like this behaviour is caused by a bug in gcc.

The workaround provided in the last comment of that bug discussion does work and solves the issue:

-Wl,--no-as-needed

Adding -lpthread fixed the identical problem for me:

 g++ -std=c++11 foo.cpp -lpthread -o foo

answer already was made for qtcreator:

LIBS += -pthread
QMAKE_CXXFLAGS += -pthread
QMAKE_CXXFLAGS += -std=c++11

for console g++: here

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

I have slightly more advanced version (4.8.4 instead of 4.8.1), and I tested all three answers above. In fact:

-pthread alone works:

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

-Wl,--no-as-needed alone does not work.

-lpthread alone does not work.

-Wl,--no-as-needed and -lpthread together work:

g++ -std=c++11 -o main -Wl,--no-as-needed main.cpp -lpthread

My version is "g++ (Ubuntu 4.8.4-2ubuntu1~14.04.1) 4.8.4".