?? commonmutex.cpp
字號(hào):
#include "CommonMutex.h"
CCommonMutex::CCommonMutex()
{
sem_init( &m_Semaphore, 0, 1 );
m_nCount = 0 ;
m_nPid = 0 ;
}
CCommonMutex::~CCommonMutex()
{
sem_destroy( &m_Semaphore );
}
void CCommonMutex::Lock()
{
//如果是鎖的持有者再次調(diào)用,則增加訪問計(jì)數(shù),否則掛起
if(m_nPid != getpid())
{
sem_wait( &m_Semaphore );
m_nPid = getpid();
}
m_nCount++;
}
bool CCommonMutex::tryLock()
{
if(m_nPid != getpid())
{
if(sem_trywait( &m_Semaphore )==0)
{
m_nPid = getpid();
m_nCount++;
return TRUE ;
}
else
{
return FALSE ;
}
}
else
{
m_nCount++;
return TRUE ;
}
}
void CCommonMutex::Unlock()
{
if(m_nPid == getpid())
{
if(m_nCount == 1)
{
//鎖的持有者最后一次調(diào)用unlock
m_nPid = 0 ;
}
if(m_nCount > 0)
{
//減少持有者對(duì)鎖的訪問計(jì)數(shù)
m_nCount--;
}
if(m_nCount == 0)
//當(dāng)訪問計(jì)數(shù)為0時(shí),釋放鎖
sem_post( &m_Semaphore );
}
}
?? 快捷鍵說(shuō)明
復(fù)制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號(hào)
Ctrl + =
減小字號(hào)
Ctrl + -