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);
블로그 이미지

요다할아범

,