Implementation of thread mutex: Windows has two methods: mutex and critical section, and Linux has a mutex lock for the pthread library. Windows Thread Synchronization generally uses the critical section.
 
This article mainly discusses the differences between Windows and Linux mutex locks.
 
 
 
Windows: The same thread can repeatedly enter the same critical section (of course, multiple exits) without being blocked by the system.
 
Linux: The same thread cannot repeatedly enter the same critical section. Otherwise, the thread is blocked.
 
 
 
The following is a Windows/Linux thread mutex class I wrote.
 
################### Llock. h #####################
 
/*************************************** *****************************
Created on: 2004/09/02
File Name: llock. h
Author: Liu Lei (Vietor)
Version: 1.0
Email: liuleilover@163.com
 
Purpose:
Windows/Linux common thread mutex lock class. Note the following:
Windows: The same thread can repeatedly enter the same mutex (of course, multiple exits) without being blocked by the system.
Linux: The same thread cannot repeatedly enter the same critical section. Otherwise, the thread is blocked.
 
Copyright:
You can copy and use copies of this program at will, but please ensure that all files are complete and
It is not modified. If you have any suggestions, contact the author.
 
**************************************** *****************************/
 
# Ifndef _ llock _
# DEFINE _ llock _
 
# Ifdef _ Win32
# Include <windows. h>
# Else
# Include <pthread. h>
# Endif
 
// Mutex lock
 
Class llock
{
Public:
 
Inline llock (void)
{
M_binit = true;
# Ifdef _ Win32
: Initializecriticalsection (& m_lock );
# 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 (entering the mutex lock)
Inline void lock (void)
{
If (m_binit)
{
# Ifdef _ Win32
: Entercriticalsection (& m_lock );
# Else
: Pthread_mutex_lock (& m_lock );
# Endif
}
}
// Unlock (leave the mutex lock)
Inline void unlock (void)
{
If (m_binit)
{
# Ifdef _ Win32
: Leavecriticalsection (& m_lock );
# Else
: Pthread_mutex_unlock (& m_lock );
# Endif
}
}
 
PRIVATE:
Bool volatile m_binit;
# Ifdef _ Win32
Critical_section m_lock;
# Else
Pthread_mutex_t m_lock;
# Endif
};
 
// Automatically lock the class (used in inline mode)
 
Class lautolock {
Public:
Inline lautolock (llock & lock): m_lock (LOCK)
{
M_lock.lock ();
}
Inline ~ Lautolock ()
{
M_lock.unlock ();
}
PRIVATE:
Llock & m_lock;
};
 
# Endif