吉林-小伙(694129464) 19:59:24
class CReadWriteLock
{
private:
int m_nReadCount;
pthread_mutex_t m_mutexRead;
pthread_mutex_t m_mutexWrite;
public:
CReadWriteLock():m_nReadCount(0)
{
pthread_mutex_init(&m_mutexRead, NULL);
pthread_mutex_init(&m_mutexWrite, NULL);
}
~CReadWriteLock()
{
pthread_mutex_destroy(&m_mutexRead);
pthread_mutex_destroy(&m_mutexWrite);
}
public:
void LockRead()
{
pthread_mutex_lock(&m_mutexRead);
m_nReadCount++;
if(m_nReadCount == 1)
{
pthread_mutex_lock(&m_mutexWrite);
}
pthread_mutex_unlock(&m_mutexRead);
printf("read lock\n");
}
void UnlockRead()
{
pthread_mutex_lock(&m_mutexRead);
m_nReadCount--;
if(m_nReadCount == 0)
{
pthread_mutex_unlock(&m_mutexWrite);
}
pthread_mutex_unlock(&m_mutexRead);
printf("read unlock\n");
}
void LockWrite()
{
pthread_mutex_lock(&m_mutexWrite);
printf("write lock\n");
}
void UnlockWrite()
{
pthread_mutex_unlock(&m_mutexWrite);
printf("write unlock\n");
}
};
深圳-C/C++傳奇(605934668) 20:03:45
posix有現(xiàn)成的讀寫(xiě)mutex
吉林-小伙(694129464) 20:03:57
我昨天搜索了一下資料 的確有
吉林-小伙(694129464) 20:06:42
phtread_rwlock_init
pthread_rwlock_destroy
吉林-小伙(694129464) 20:38:21
靠 我說(shuō)用 rwlock 怎么不死鎖了呢
我以為我用錯(cuò)了呢
原來(lái)是死鎖 會(huì)返回 一個(gè)35錯(cuò)誤碼
程序還會(huì)執(zhí)行
更高級(jí)一點(diǎn)
伙神的實(shí)現(xiàn)中,邏輯主要幾種在讀鎖,寫(xiě)鎖是“被動(dòng)模式”。讀鎖根據(jù)讀鎖次數(shù)操作寫(xiě)鎖狀態(tài)。讀鎖保證,當(dāng)讀鎖操作>0的時(shí)候?qū)戞i是鎖住的,當(dāng)讀鎖==0的時(shí)候?qū)戞i是解開(kāi)的。