miraclemiracle.blog.chinaunix.net
laoliulaoliu
C++,python,热爱算法和机器学习
全部博文(1214)
2021年(13)
2020年(49)
2019年(14)
2018年(27)
2017年(69)
2016年(100)
2015年(106)
2014年(240)
2013年(5)
2012年(193)
2011年(155)
2010年(93)
2009年(62)
2008年(51)
2007年(37)
zsszss00
bl竹子
Bean_lee
猫羲
gx303841
twlkyao
gadfly02
北大未名
五岳之巅
wb123456
一川风
Fennn
风林火山
km康蒙92
丸喵喵
格伯纳
孙河小硕
wojiuzhu
分类: C/C++
2010-12-13 10:10:14
#include <pthread.h> struct rwlock { pthread_mutex_t lock; pthread_cond_t read, write; unsigned readers, writers, read_waiters, write_waiters; }; void reader_lock(struct rwlock *self) { pthread_mutex_lock(&self->lock); if (self->writers || self->write_waiters) { self->read_waiters++; do pthread_cond_wait(&self->read, &self->lock); while (self->writers || self->write_waiters); self->read_waiters--; } self->readers++; pthread_mutex_unlock(&self->lock); } void reader_unlock(struct rwlock *self) { pthread_mutex_lock(&self->lock); self->readers--; if (self->write_waiters) pthread_cond_signal(&self->write); pthread_mutex_unlock(&self->lock); } void writer_lock(struct rwlock *self) { pthread_mutex_lock(&self->lock); if (self->readers || self->writers) { self->write_waiters++; do pthread_cond_wait(&self->write, &self->lock); while (self->readers || self->writers); self->write_waiters--; } self->writers = 1; pthread_mutex_unlock(&self->lock); } void writer_unlock(struct rwlock *self) { pthread_mutex_lock(&self->lock); self->writers = 0; if (self->write_waiters) pthread_cond_signal(&self->write); else if (self->read_waiters) pthread_cond_broadcast(&self->read); pthread_mutex_unlock(&self->lock); } void rwlock_init(struct rwlock *self) { self->readers = self->writers = self->read_waiters = self->write_waiters = 0; pthread_mutex_init(&self->lock, NULL); pthread_cond_init(&self->read, NULL); pthread_cond_init(&self->write, NULL); }
上一篇:C语言面向对象编程
下一篇:[转]深析C++析构函数
登录 注册