#define CHECK(_sem) (sem_init(&(_sem)->sem, (pshared), (value)) == 0) ? ((_sem)->valid = true, 0) : ((_sem)->valid = false, -1)
然后使用的地方为
ret = CHECK(_sem)
也就是说,sem_init返回0时,_sem->valid被设置成true, ret被设置为0,
sem_init返回非0时,_sem->valid被设置成false, ret被设置为-1
struct rwlock
{
sem_t read
sem_t write
int reads
}
void RWLock_Init(rwlock &lock)
{
sem_init(lock.read, 0, 1)
sem_init(lock.write, 0, 1)
lock.reads = 0
}
void Acquir_read_lock(rwlock &lock)
{
sem_wait(&lock.read)
++lock.reads
if(lock.reads == 1)
{
sem_wait(&lock.write)
}
sem_post(&lock.write)
}
void acquir_read_unlock(rwlock &lock)
{
sem_wait(&lock.read)
--lock.reads
if(lock.reads == 0)
{
sem_post(&lock.write)
}
sem_post(&lcok.read)
}
void acquir_write_lock(rwlock &lock)
{
sem_wait(&lock.write)
}
void acquir_write_unlock(rwlock * lock)
{
sem_post(&lock.write)
}
欢迎分享,转载请注明来源:夏雨云
评论列表(0条)