我正在编写一个简单的 C++ 程序来演示锁的使用。我正在使用 codeblocks
和 gnu
gcc
编译器。
#include <iostream>
#include <thread>
#include <mutex>
using namespace std;
int x = 0; // shared variable
void synchronized_procedure()
{
static std::mutex m;
m.lock();
x = x + 1;
if (x < 5)
{
cout<<"hello";
}
m.unlock();
}
int main()
{
synchronized_procedure();
x=x+2;
cout<<"x is"<<x;
}
我收到以下错误:命名空间 std 中的互斥量没有命名类型
。
为什么会出现此错误? 编译器不支持使用锁吗?
最佳答案
我碰巧遇到了同样的问题。 GCC 在 Linux 下与 std::mutex
一起工作得很好。但是,在 Windows 上,情况似乎更糟。在 MinGW GCC 4.7.2 附带的 #if
保护下定义的:
#if defined(_GLIBCXX_HAS_GTHREADS) && defined(_GLIBCXX_USE_C99_STDINT_TR1)
很遗憾,_GLIBCXX_HAS_GTHREADS
未在 Windows 上定义。运行时支持根本不存在。
您可能还想直接在 MinGW 邮件列表上提问,以防 GCC 专家可以帮助您。
编辑:MinGW-w64 项目提供了必要的运行时支持。查看 http://mingw-w64.sourceforge.net/和 https://sourceforge.net/projects/mingw-w64/files/ .另外,正如 0xC0000022L 所指出的,您需要下载 POSIX 线程版本(我上次没有提到)。
关于命名空间 std 中的 C++ 互斥锁未命名类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14191566/