Mutex C++

Mutex wrapper on C++98 pthread mutex and a the better C++11 std::mutex solution

24/04/2014 Available in es C++pthreadMutex

C++11 has added many improvements to help us developing multi-thread systems. I’m going to talk about Mutex.

In previous C++11 compiler versions, we can get a pthread Mutex, but we must initialize it and destroy it in old C style, in the end you must do more things than just lock/unlock.

With C++11 Mutex Class, we just lock/unclock the object.

#include <mutex>

std::mutex mtx;

void do_something (int i) {
  // critical section

Or you can just use Mutex with a generic lock guard.

If you still have to stick to previous C++11 compiler versions, maybe it is useful to you a wrapper class I created that helps you to work with pthread Mutex, so you just have to lock/unlock the Mutex object: Gist code.