我有一些線程來寫資源和一些讀取它。但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