吉林-小伙(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的时候写锁是解开的。