我将其编写为多线程示例的简化版本,以了解它,但是在编译时遇到了一些问题。我的编译器说thread
不是std
的成员,并提示我将#include <thread>
添加到代码中,即使我已经这样做了。到目前为止,我一直找不到任何类似的问题,但是我怀疑这与我的编译方式有关,因为我的代码与示例代码非常相似。
#include <iostream>
#include <thread>
void doWork () {
std::cout << "Working...\n";
}
int main () {
std::thread worker(doWork);
work.join();
std::cout << "Finished\n";
return 0;
}
我的编译器是MinGW g ++ 9.2.0
我使用g++ main.cpp -o main
进行编译,它给了我这些错误:
main.cpp: In function 'int main()':
main.cpp:9:7: error: 'thread' is not a member of 'std'
9 | std::thread worker(doWork);
| ^~~~~~
main.cpp:3:1: note: 'std::thread' is defined in header '<thread>'; did you forget to '#include <thread>'?
2 | #include <thread>
+++ |+#include <thread>
3 |
main.cpp:11:2: error: 'work' was not declared in this scope
11 | work.join();
| ^~~~
答案 0 :(得分:7)
默认情况下,MinGW-w64附带本机(Win32)而不是POSIX线程支持,但是不幸的是,当前没有Win32 gthreads实现(libstdc ++的线程子系统),因此GCC中没有线程功能。
您需要从x86_64-w64-mingw32-g++-win32
切换到x86_64-w64-mingw32-g++-posix
软件包,以使std::thread
在MinGW-w64中工作。
问题mingw-w64 threads: posix vs win32详细讨论了此问题。