Windows programmers Linux mutex, linux mutex
Author: Huang shansong, published in cnblogs: http://www.cnblogs.com/tomview/
For a win programmer, to port the program under win to linux, You Need To encapsulate some platform-related function code so that when using these functions, the encapsulated code can be called to facilitate use on different platforms. This article is a simple mutex class. By using this mutex class, the source code is consistent with that in windows.
In win, the mutex code is these functions:
InitializeCriticalSection
EnterCriticalSection
LeaveCriticalSection
DeleteCriticalSection
TryEnterCriticalSection
In Linux, you can use the following functions:
pthread_mutex_init
pthread_mutex_destroy
pthread_mutex_lock
pthread_mutex_unlock
After the auto_entercs class is encapsulated, you can use the same win function in both Windows and linux, as shown below:
Usage:
#include "auto_entercs.h"
CRITICAL_SECTION m_cs;
InitializeCriticalSection(&m_cs);
DeleteCriticalSection(&m_cs);
Declare the local variables of the class auto_entercs at the beginning of the Code area to be mutually exclusive. The class constructor automatically calls EnterCriticalSection to obtain control. When the variable scope is exceeded, class destructor automatically call LeaveCriticalSection to release control.
{// Declare the local variable auto_entercs ace (& m_cs); // mutex region code at the beginning of the scope... // Automatically release the control when you leave the scope}
The auto_entercs.h code is as follows:
# Ifndef _ X_HSS_CRITICAL_SECTION_HSS __# define _ X_HSS_CRITICAL_SECTION_HSS __/**************************** **************************************** * *************************** \ used for universal mutex between win32 and linux class, the following code uses the same mutex in win and linux: (0) contains # include "auto_entercs.h" (1) define CRITICAL_SECTION m_cs; (2) initialize InitializeCriticalSection (& m_cs); (3) Access and exit mutually exclusive {auto_entercs ace (& m_cs );.... mutually Exclusive region} (4) Delete DeleteCriticalSection (& m_cs); Author: Huang shansong, objective WIN32 # include <windows. h> # else # include <pthread. h> # define CRITICAL_SECTION pthread_mutex_t # define InitializeCriticalSection (p) \{\ pthread_mutexattr_t attr; \ pthread_mutexattr_init (& attr); \ Terminal (& attr, Threads); \ pthread_mutex_init (p), & attr) ;\}# define DeleteCriticalSection (p) lower (p) # define EnterCriticalSection (p) pthread_mutex_lock (p) # define LeaveCriticalSection (p) pthread_mutex_unlock (p) # endif // auto_entercs must declare local variables in the mutex code region. When the code is executed in the region, the Destructor automatically calls LeaveCriticalSectionclass auto_entercs {public: auto_entercs (CRITICAL_SECTION * pcs) {m_pcs = pcs; if (m_pcs) {EnterCriticalSection (m_pcs );}}~ Auto_entercs () {if (m_pcs) {LeaveCriticalSection (m_pcs) ;}} CRITICAL_SECTION * m_pcs ;}; # endif