命名空间std中的C++ mutex没有命名类型

arj*_*jun 24 c++ multithreading locking mingw compiler-errors

我正在编写一个简单的C++程序来演示锁的使用.我正在使用codeblocksgnu 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;
}
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:mutex in namespace std does not name a type.

为什么我收到此错误?编译器是否支持使用锁?

Yon*_* Wu 16

我碰巧看着同样的问题.GCC std::mutex在Linux下运行良好.然而,在Windows上似乎情况更糟.在MinGW GCC 4.7.2附带的<mutex>头文件中(我相信你也使用了MinGW GCC版本),我发现互斥类是在以下#if守护下定义的:

#if defined(_GLIBCXX_HAS_GTHREADS) && defined(_GLIBCXX_USE_C99_STDINT_TR1)
Run Code Online (Sandbox Code Playgroud)

遗憾的是,_GLIBCXX_HAS_GTHREADSWindows上没有定义.运行时支持根本不存在.

您可能还想直接在MinGW邮件列表中提问,以防一些GCC专家帮助您.

编辑:MinGW-W64项目提供必要的运行时支持.查看http://mingw-w64.sourceforge.net/

  • 事实证明,即使使用MinGW64,您也必须使用后缀为-posix的与GCC相关的工具,而不是`-win32` ...,后者显然是指所使用的线程模型。 (2认同)

Ami*_*yan 15

对 MINGW 使用 POSIX 线程模型:

$ sudo update-alternatives --config i686-w64-mingw32-gcc
<choose i686-w64-mingw32-gcc-posix from the list>

$ sudo update-alternatives --config i686-w64-mingw32-g++
<choose i686-w64-mingw32-g++-posix from the list>

$ sudo update-alternatives --config x86_64-w64-mingw32-gcc
<choose x86_64-w64-mingw32-gcc-posix from the list>

$ sudo update-alternatives --config x86_64-w64-mingw32-g++
<choose x86_64-w64-mingw32-g++-posix from the list>
Run Code Online (Sandbox Code Playgroud)

另请参阅:mingw-w64 线程:posix 与 win32

  • 在 debian buster 上测试良好。这正是我所需要的。`-std=c++0x` 解决方案现在已经过时了,因为它现在是不必要的(至少从 gcc 8.3 开始)。 (2认同)

Int*_*uAi 13

这已经包含在MingW(版本2013072300)中.要包含它,您必须在MinGW Installation Manager中选择pthreads包.

来自MingW Installation Manager的Pthreads包选项

  • 抱歉:Windows,mingw32-pthreads-w32 2.10-pre-20160821-1,这似乎是我们可以更新到的最新版本;仍然说 `std::mutex 没有命名类型` (4认同)

小智 6

至少,Mutex在Mingw-builds工具链的'Thread model:win32'中不受支持.您必须使用'Thread model:posix'选择任何工具链.在尝试了几个版本和修订版(架构i686和x86_64)之后,我只发现x86_64-4.9.2-posix-seh-rt_v3-rev1中的支持是线程模型,即IMO,决定因素.


Kol*_*nya -9

标准线程库的许多类都可以用 boost 类替换。mutex一个非常简单的解决方法是用几行更改整个标准文件。

#include <boost/thread.hpp>

namespace std
{
   using boost::mutex;
   using boost::recursive_mutex;
   using boost::lock_guard;
   using boost::condition_variable;
   using boost::unique_lock;
   using boost::thread;
}
Run Code Online (Sandbox Code Playgroud)

并且不要忘记链接到 boost 线程库。

  • 这可能太多了,特别是如果你不使用 boost (4认同)
  • 像这样扩展“std”命名空间会产生 UB。http://en.cppreference.com/w/cpp/language/extending_std (3认同)