读写锁 rwlock 实现里的避免写锁饥饿问题
使用读写锁时,同一时刻可以有多个读锁占用,但只能有一个写锁占用。
使用 pthread 多线程时,需要考虑如果持续地有多个线程在获得和释放读锁,这时写锁的请求是否会一直等待,得不到机会。实际是不会,读写锁 pthread_rwlock 在实现时,考虑了写锁请求一直等待导致写锁饥饿的问题。实际在等待获得写锁时,实现里会添加判断:如果锁已经被占用,则写锁请求进入等待状态,并在等待队列的优先位置排队;并且,如果是读锁正在占用,在写锁请求等待时,后续新的读锁请求也要排队等待,而不是直接占用读锁;直到锁有空,并获得写锁,这样就避免了写锁饥饿的问题。
以下是手册里的部分描述:
$ man pthread_rwlock_rdlock
The pthread_rwlock_rdlock() function shall apply 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.
$ man pthread_rwlock_wrlock
Implementations may favor writers over readers to avoid writer starvation.