Critical Section - Windows vs Linux in C++

Just to provide a simple equivalent critical section code between Windows and Linux

For Windows, critical section code are located at WinBase.h. Normally, you do not need to include this header as it is pre-loading in VS compiler

For Linux, mutex code are located in pthread.h. You will have to include this header file in order to use mutex in Linux

Creating critical section variable

This variable will be the object to be acquired when you want to use any critical resource

On Windows

CRITICAL_SECTION cs;

On Linux

pthread_mutex_t m;


Initializing critical section

You have to initialize the critical section resource before using

On Windows

InitializeCriticalSection(&cs);

On Linux

//create mutex attribute variable
pthread_mutexattr_t mAttr;

// setup recursive mutex for mutex attribute
pthread_mutexattr_settype(&mAttr, PTHREAD_MUTEX_RECURSIVE_NP);

// Use the mutex attribute to create the mutex
pthread_mutex_init(&m, &mAttr);

// Mutex attribute can be destroy after initializing the mutex variable
pthread_mutexattr_destroy(&mAttr)


Enter and Leave critical section

They always use in a pair. Critical resource should be placed within the critical section

Windows

EnterCriticalSection(&cs);

LeaveCriticalSection(&cs);


Linux

pthread_mutex_lock (&m);


pthread_mutex_unlock (&m);

Destroy critical section

You have to release the critical section when it is no long required

On Windows

DeleteCriticalSection(&cs);

On Linux

pthread_mutex_destroy (&m);

Comments

  1. Thank you, this is exactly what i was looking for!

    ReplyDelete
  2. Hello Thompson,
    I found this helpful as well. However, why did you choose PTHREAD_MUTEX_RECURSIVE_NP instead of PTHREAD_MUTEX_NORMAL?

    Thanks,
    Mike

    ReplyDelete
  3. It is just an example. You can use either of them depend on your use case

    PTHREAD_MUTEX_NORMAL is usually the default and only allow thread to acquires onces

    PTHREAD_MUTEX_RECURSIVE is a recursive mutex that allow thread to acquire many time. But, you need to release the lock the same amount of time before other can reuse it.

    ReplyDelete
  4. Thanks Thompson, this is very helpful. Just what I was looking for.

    ReplyDelete

Post a Comment

Popular Posts