C++ mutex in namespace std does not name a type

arjun picture arjun · Jan 7, 2013 · Viewed 64.2k times · Source

I'm writing a simple C++ program to demonstrate the use of locks. I am using codeblocks and gnu gcc compiler.

 #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;
}

I'm getting the following error: mutex in namespace std does not name a type.

Why am I getting this error? Doesn't the compiler support use of locks?

Answer

Yongwei Wu picture Yongwei Wu · Aug 1, 2013

I happened to be looking at the same problem. GCC works fine with std::mutex under Linux. However, on Windows things seem to be worse. In the <mutex> header file shipped with MinGW GCC 4.7.2 (I believe you are using a MinGW GCC version too), I have found that the mutex class is defined under the following #if guard:

#if defined(_GLIBCXX_HAS_GTHREADS) && defined(_GLIBCXX_USE_C99_STDINT_TR1)

Regretfully, _GLIBCXX_HAS_GTHREADS is not defined on Windows. The runtime support is simply not there.

You may also want to ask questions directly on the MinGW mailing list, in case some GCC gurus may help you out.

EDIT: The MinGW-w64 projects provides the necessary runtime support. Check out http://mingw-w64.sourceforge.net/ and https://sourceforge.net/projects/mingw-w64/files/. Also, as 0xC0000022L pointed out, you need to download the POSIX thread version (I missed mentioning it last time).