Introduction
This is my first article so .... here I go. :)
Using the code
Mutual exclusion (often abbreviated to mutex) is used in concurrent programming to avoid the simultaneous use of a common resource.
An example in wich you can use a mutex is in a multithreaded application when inserting items into a list.
The mutex implementation in windows and linux programming is a little different but with a little coding you can use the same thing for both.
To do this we will use macros like this:
#if defined(LINUX)
.....
#elif defined(WINDOWS)
.....
#endif
To use cross platform we will use a header file and a .cpp file
Let's start with the header file. The first thing we must do is to include the header files for the mutex. This files are different for windows and linux.
Here is the code:
#if defined(LINUX)
#include <pthread.h>
#elif defined(WINDOWS)
#include <windows.h>
#include <process.h>
#endif
In windows the mutex is defined as HANDLE data type while in linux we have pthread_mutex_t for the mutex.
The code should now look like this:
#if defined(LINUX)
#include <pthread.h>
#elif defined(WINDOWS)
#include <windows.h>
#include <process.h>
#endif
#if defined(LINUX)
#define MUTEX pthread_mutex_t
#elif defined(WINDOWS)
#define MUTEX HANDLE
#endif
Now we need to declare the functions that we'll use: init lock and unlock muetx. The full could should now look like this:
#if defined(LINUX)
#include <pthread.h>
#elif defined(WINDOWS)
#include <windows.h>
#include <process.h>
#endif
#if defined(LINUX)
#define MUTEX pthread_mutex_t
#elif defined(WINDOWS)
#define MUTEX HANDLE
#endif
int MUTEX_INIT(MUTEX *mutex);
int MUTEX_LOCK(MUTEX *mutex);
int MUTEX_UNLOCK(MUTEX *mutex);
Our functions will be held by the cross.cpp file:
int MUTEX_INIT(MUTEX *mutex)
{
#if defined(LINUX)
return pthread_mutex_init (mutex, NULL);;
#elif defined(WINDOWS)
*mutex = CreateMutex(0, FALSE, 0);;
return (*mutex==0);
#endif
return -1;
}
int MUTEX_LOCK(MUTEX *mutex)
{
#if defined(LINUX)
return pthread_mutex_lock( mutex );
#elif defined(WINDOWS)
return (WaitForSingleObject(*mutex, INFINITE)==WAIT_FAILED?1:0);
#endif
return -1;
}
int MUTEX_UNLOCK(MUTEX *mutex)
{
#if defined(LINUX)
return pthread_mutex_unlock( mutex );
#elif defined(WINDOWS)
return (ReleaseMutex(*mutex)==0);
#endif
return -1;
}
I will not get into the details of this functions, you can use msdn for windows and mkssoftware for linux of you desire more informations.
Using the code
First of all you need to define WINDOWS or LINUX so the compiler knows the platform. This is all you need to change when switching from windows to linux.
The code for mutexes is the same, you use it like this:
MUTEX mutex;
MUTEX_INIT(&mutex);
MUTEX_LOCK(&mutex);
MUTEX_UNLOCK(&mutex);
Conclusion
I hope you find this article to be of some use.
Article powered by Multiplex Games