嗨,我正在尝试使用std::thread
与G ++。这是我的测试代码
#include <thread>
#include <iostream>
int main(int, char **){
std::thread tt([](){ std::cout<<"Thread!"<<std::endl; });
tt.join();
}
它编译,但当我尝试运行它时,结果是:
terminate called after throwing an instance of 'std::system_error'
what(): Operation not permitted
Aborted
我的编译器版本:
$ g++ --version
g++ (Ubuntu/Linaro 4.6.1-9ubuntu3) 4.6.1
Copyright (C) 2011 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++ -std=c++0x test.cpp
$ ./a.out
我试过
$ g++ -std=c++0x -lpthread test.cpp
$ ./a.out
还是一样。
我认为在Linux上,pthread用于实现std::thread
,因此您需要指定-pthread
编译器选项。
由于这是一个链接选项,因此该编译器选项需要在源文件之后:
$ g++ -std=c++0x test.cpp -pthread
除了使用-std=c++0x
和-pthread
,你不能使用-static
。
-std=c++11 -static -pthread -Wl,--whole-archive -lpthread -Wl,--no-whole-archive
与-static
一起工作!
这是一个简单的CMake文件,用于编译使用线程的C ++ 11程序:
的CMakeLists.txt:
cmake_minimum_required(VERSION 2.8)
list(APPEND CMAKE_CXX_FLAGS "-pthread -std=c++11 ${CMAKE_CXX_FLAGS}")
add_executable(main main.cpp)
构建它的一种方法是:
mkdir -p build
cd build
cmake .. && make
尝试在单个命令中以这种方式编译:
g++ your_prog.cpp -o your_output_binary -lpthread -std=gnu++11
您也可以尝试使用C ++ 11而不是gnu ++ 11。希望这有效。