吉林-小伙(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有現成的讀寫mutex
吉林-小伙(694129464) 20:03:57
我昨天搜索了一下資料 的確有
吉林-小伙(694129464) 20:06:42
phtread_rwlock_init
pthread_rwlock_destroy
吉林-小伙(694129464) 20:38:21
靠 我說用 rwlock 怎么不死鎖了呢
我以為我用錯了呢
原來是死鎖 會返回 一個35錯誤碼
程序還會執行
更高級一點
伙神的實現中,邏輯主要幾種在讀鎖,寫鎖是“被動模式”。讀鎖根據讀鎖次數操作寫鎖狀態。讀鎖保證,當讀鎖操作>0的時候寫鎖是鎖住的,當讀鎖==0的時候寫鎖是解開的。