About WindowsLinux thread mutual exclusion

xiaoxiao2021-03-06  67

Implementation of thread mutual exclusion: Windows has two methods for muters and critical regions, Linux has a mutex of PThread library. Windows threads are generally used in critical regions.

This is mainly discussed here to discuss the difference between the Windows critical region and Linux mutex.

Windows: The same thread can be repeated into the same critical area (of course, leave multiple times), and the thread is not blocked by the system.

Linux: The same thread cannot be repeated into the same critical area. Otherwise the thread is blocked.

Below is a Windows / Linux General Thread Mutual Realism I wrote

######################################################################################################################################################################################################################################################################################################

/ ************************************************** ******************* creation date: 2004/08/30 file name: llock.h author: Liu Lei (vietor) version: 1.0 E-mail: liuleilover@163.com

Create a purpose: Windows / Linux universal thread mutex lock class. Note the following two points: Windows: The same thread can repeat the same mutual exclusion (of course, it is also necessary to leave multiple times), and the thread is not blocked by the system. Linux: The same thread cannot be repeated into the same critical area. Otherwise the thread is blocked.

Copyright Notice: You can copy and use the copy of this program at will, but please ensure that all files are complete and not modified, if you have a modified opinion, please contact the author. *********************************************************** ****************** /

#ifndef _llock_ # Define _llock_

#ifdef _win32 # include # else # include #ENDIF // mutually exclusive lock class

Class llock {public:

Inline llock (void) {m_binit = true; #ifdef _win32 :: initializecriticalsection; # else :: pthread_mutex_init (& m_lock, null); # endif}

inline ~ llock (void) {if (m_bInit) {m_bInit = false; #ifdef _WIN32 :: DeleteCriticalSection (& m_lock); # else :: pthread_mutex_destroy (& m_lock); # endif}} // lock (mutex enter) inline void Lock (void) {if (m_binit) {#ifdef _win32 :: entercriticalsection; # else :: pthread_mutex_lock (& ​​m_lock); # Endif}} // Unlock (left mutual exclusion lock) Inline void unlock (void) {iF (m_binit) {#ifdef_win32 :: LeavecriticalSection (& M_LOCK); # else :: pthread_mutex_unlock; # endif}}

Private: bool volatile m_binit; #ifdef _win32 critical_section m_lock; #else pthread_mutex_t m_lock; #ENDIF};

// Auto lock class (inline manner) Class Lautolock {public: inline lautolock (LLOCK & LOCK): M_Lock (LOCK) {m_lock.lock ();} inline ~ Lautolock () {m_lock.unlock ();} private: LLOCK & M_LOCK;

#ENDIF

转载请注明原文地址:https://www.9cbs.com/read-120634.html

New Post(0)