我有一些线程来写资源和一些读取它。但pthread_rwlock导致大量的上下文切换。所以我想象一种避免它的方法。但我不确定它是否安全。原子变量可以代替pthread_rwlock吗?它可以锁无
这是代码:
sig_atomic_t slot = 0;
struct resource {
sig_atomic_t in_use; /*Counter,if in_use, not zero*/
.....
} xxx[2];
int read_thread()
{
i = slot; /*avoid slot changes in process */
xxx[i].in_use++;
read(xxx[i]);
xxx[i].in_use--;
}
int write_thread()
{
mutex_lock; /*mutex between write threads */
if (slot == 0) {
while(xxx[1].in_use != 0); /*wait last read thread in slot 1*/
clear(xxx[1]);
write(xxx[1]);
slot = 1;
} else if (slot == 1) {
while(xxx[0].in_use != 0);
clear(xxx[0]);
write(xxx[0]);
slot = 0;
}
mutex_unlock;
}
威尔的作品?成本是2倍存储和3个原子变量。 非常感谢!
什么阻止在阅读时进行阅读?阅读从不等待。 – stark
单线程内存屏障环形缓冲区如何? – 2012-07-03 08:48:36