使用 g++ 编译多线程代码
Compiling multithread code with 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
等小东西
.PPS:
$ 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) 它可以编译并运行良好
PPPPS:伙计们,它不是在 Linux 下在 GCC 中使用 std::thread 的正确链接选项是什么的副本?
购买力平价:
$ dpkg --get-selections | grep 'libc.*dev'
libc-dev-bin install
libc6-dev:amd64 install
libclang-common-dev install
linux-libc-dev:amd64 install
答案是由SO聊天C++的一位好心成员提供的。
看起来这种行为是由 gcc 中的错误引起的。
该错误讨论的最后一条评论中提供的解决方法确实有效并解决了该问题:
-Wl,--no-as-needed
添加-lpthread
为我解决了相同的问题:
g++ -std=c++11 foo.cpp -lpthread -o foo
我有稍微高级的版本(4.8.4而不是4.8.1),我测试了上面的三个答案。 事实上:
-pthread
单独有效:
g++ -std=c++11 -o main -pthread main.cpp
仅靠-Wl,--no-as-needed
是行不通的。
仅靠-lpthread
是行不通的。
-Wl,--no-as-needed
和-lpthread
一起工作:
g++ -std=c++11 -o main -wl,--no-as-need main.cpp -lpthread
我的版本是"g++ (Ubuntu 4.8.4-2ubuntu1~14.04.1) 4.8.4"。
答案已经给出对于 qtcreator:
LIBS += -pthread
QMAKE_CXXFLAGS += -pthread
QMAKE_CXXFLAGS += -std=c++11
对于控制台 G++:此处
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
相关文章:
- 删除原子多线程代码中的容器
- Visual Studio 发布模式阻止在调试模式下执行的代码.使用 WinHTTP 和多线程
- 开始多线程代码之前的初始化
- 实现在多线程代码中安全恢复的断点
- 一个简单的 win32 多线程代码.这能行吗?
- 混合开放MP/MPI代码中的多线程发送/接收时出错
- 为什么我的特征代码不使用更多线程扩展
- 需要帮助识别简单多线程代码中的错误
- 从C 启动多线程Python代码
- 多线程和单线程代码维护
- 在多线程代码中转发
- 为什么此 C++ 多线程互斥代码偶尔会出现故障?
- C++多线程性能比单线程代码慢
- 如何将此代码重构为多线程版本
- 为什么重新执行我的多线程代码后输出不一样
- boost::shared_ptr代码中的多线程错误
- 在多线程应用程序中的蜘蛛猴中嵌入javascript代码
- 如何改进此代码以便在多线程环境下运行
- 多线程提升 Python C++ PySide 中的代码
- C++中的单线程多线程代码