对一个同享的数据布局,读的频率远弘远于写,所以用了读写锁.但是发现写线程老是抢不到锁.
按The Open Group 的Single UNIX? Specification所说,"Thepthread_rwlock_rdlock() function applies a read lock to the read-write lock referenced by rwlock. The calling thread acquires the read lock if a writer does not hold the lock and there are no writers blocked on the lock. It is unspecified whether the calling thread acquires the lock when a writer does not hold the lock and there are writers waiting for the lock" 貌似意思是说,没有writer在持有写锁的时,reader是可以拿到读锁的。然则没有划定,若是有writer在等写锁,该若何?
自己测试结果:
对于ACE_RW_Mutex,当几个线程不断获取释放读锁,各读线程使用锁的时间叠加,锁讲一直处于被读取状态,此时加写锁,写线程将一直处于等待状态。
即ACE_RW_Mutex 并不保证读写锁请求和处理时序。读锁获条件是只要当前锁没有被别人以写方式获取就可以获取到读权限。这样做的优势是由于读锁可并发执行,提高CPU利用率。缺点是在读锁使用频度较高情况下,会出现不断有线程使用读锁,写锁线程饥饿等待。
pthread_rwlockattr_setkind_np 应该可以调整读写锁优先级顺序。
示例如下:
pthread_rwlockattr_t attr;
pthread_rwlockattr_init(&attr); pthread_rwlockattr_setkind_np (&attr, PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP); (void)pthread_rwlock_init(&rwlock, &attr);