c++ - 为什么我的编译器不能识别 #include <thread> (c++)?

标签 c++ multithreading mingw

我将其作为多线程示例的简化版本编写以了解它,但在编译时遇到了一些问题。我的编译器说 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();
      |  ^~~~

最佳答案

默认情况下,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更详细地讨论这个问题。

关于c++ - 为什么我的编译器不能识别 #include <thread> (c++)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63582175/

相关文章:

c++ - Windows 中的符号可见性

c++ - 无法解析函数 'GetRawInputDeviceList'

c++ - 使用带有自定义构造函数的 std::set 的自定义比较器

C# HTTPWebRequest 多线程

java - 如何每 2 分钟调用一个方法直到它返回 true?

c++ - gcc优化对具有明显常量变量的循环的影响

c++ - 为 C/C++ 设置 Windows 构建环境的最佳方法

c++ - 递归 C++ 函数,它将整数数组 n 作为输入,然后在不使用任何循环的情况下打印数组中的最大值和最小值

c++ - 信号量不适用于线程

c++ - Qt QTextBrowser 如何捕获文本并更改其光标