我安装了 mingw32-pthreads-w32 但我仍然无法编译 std::mutex

I installed mingw32-pthreads-w32 but I still cannot compile std::mutex

根据此处关于堆栈溢出的建议,我安装了 mingw32 pthread 包:

但我仍然无法使用 C++11 多线程编译代码:

 error: 'mutex' in namespace 'std' does not name a type

我使用 makefile,我使用 mingw32-make 执行它,它使用位于 C:\MinGW\bin\g++.exe.

g++

G++ 版本:g++.exe (GCC) 5.3.0 Mingw32制作版本:GNU Make 3.82.90,Built for i686-pc-mingw32

我使用 -M 选项生成已用 headers 的列表,这就是我得到的:

 c:\mingw\lib\gcc\mingw32.3.0\include\c++\thread \
 c:\mingw\lib\gcc\mingw32.3.0\include\c++\mutex \

我什至不确定这些是否正确headers。

有什么问题吗?我该如何解决这个问题?

Windows 的 GCC 带有两个线程模型:win32 和 posix。只有 posix 线程模型支持标准多线程库。

要检查这一点,请尝试 运行 g++ -v。如果您没有看到 --enable-thread=posix,则表示您的编译器套件不支持标准多线程库。

您可以从 https://sourceforge.net/projects/mingw-w64/ 下载 Mingw64 GCC,它们是用 --enable-thread=posix.

构建的

请注意,尽管 --enable-thread=posix 意味着您可以使用标准的多线程库,但执行起来比直接使用 Win32 API 如 CreateThread 慢得多。这是因为对于 GCC,std::thread 等是在 gthread 之上实现的,gthread 是基于 pthread 实现的。因为Windows不支持pthread,Mingw64团队用Win32API实现了pthread。你可以看到你需要支付相当多的抽象债务。

如果性能对您很重要,您可能不想使用它。您还需要将 winpthread.dll 分发给最终用户,因为静态 link 将不起作用。

如果你想让你的代码在所有平台上工作,使用它是可以的。