在 Windows 10 上使用 C++ 线程的问题(使用 g++ 作为编译器)

Mat*_*att 6 c++ multithreading g++

我正在尝试创建一个线程并让它向终端打印一些东西。我遇到了一些问题,所以我决定采用其他人制作的这段非常简单的代码,当我编译它时,我得到了下面列出的错误,但其他人在线运行似乎没有问题。

#include <iostream>
#include <thread>

using namespace std;

void hello_world()
{
    cout << "Hello from thread!\n";
}

int main()
{
    thread threadobj1(hello_world);
    threadobj1.join();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

编译器(Windows 10 上的 mingw32-gcc-g++-bin 8.2.0.3)给出以下错误:

.\multiT.cpp: In function 'int main()':
.\multiT.cpp:13:5: error: 'thread' was not declared in this scope
     thread threadobj1(hello_world);
     ^~~~~~
.\multiT.cpp:13:5: note: 'std::thread' is defined in header '<thread>'; did you forget to '#include <thread>'?.\multiT.cpp:3:1:
+#include <thread>

.\multiT.cpp:13:5:
     thread threadobj1(hello_world);
     ^~~~~~
.\multiT.cpp:14:5: error: 'threadobj1' was not declared in this scope
     threadobj1.join();
     ^~~~~~~~~~
.\multiT.cpp:14:5: note: suggested alternative: 'thread_local'
     threadobj1.join();
     ^~~~~~~~~~
     thread_local
Run Code Online (Sandbox Code Playgroud)

我希望有人能帮我弄清楚为什么这对我不起作用,错误说我应该包含 ,但我显然已经这样做了,所以我现在有点迷茫。我已经尝试安装“mingw32-pthreads-w32-dev”软件包,因为它们没有安装,但这没有任何区别。我还向编译器添加了以下参数:

g++ -std=c++14 -pthread .\multiT.cpp
Run Code Online (Sandbox Code Playgroud)

Mat*_*att 3

对于处理此问题的其他人:最简单的解决方案是下载mingw-64并使用他们的编译器。

然后使用-std=gnu++11-std=c++11参数来启用对 ISO C++ 2011 标准的支持以及对线程的扩展支持(请注意:此支持目前处于实验阶段,尽管到目前为止还没有给我带来任何问题)。