Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 438
arjun Avatar asked Jan 07 '13 07:01

arjun


2 Answers

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).

like image 146
Yongwei Wu Avatar answered Nov 08 '22 10:11

Yongwei Wu


Use POSIX threading model for MINGW:

$ 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>

See also: mingw-w64 threads: posix vs win32

like image 21
Amir Saniyan Avatar answered Nov 08 '22 10:11

Amir Saniyan