Linux read-write lock implementation tutorial

  
 

To implement read-write locks, you must first know the characteristics of the read-write locks, except that the readers can be concurrent, and the writers must exclude them. Also consider the issue of avoiding writer hunger. After comprehensive consideration, the implementation of the read-write lock can be summarized as the following four points: 1. When the write lock has been applied, the read lock write lock cannot be applied (the write lock can only be locked once) 2. When the read has been applied When locking, you can continue to apply the read lock, but you can't apply the write lock. 3. If you have a waiter, you can't get the read lock (guarantee writer priority). 4. When unlocking, if the writer is waiting, the reader cannot be woken up. We use mutexes and condition variables to implement read-write locks, which is how most systems are implemented. In addition, this article mainly wants to explain the implementation of the read-write lock, so here only achieve the most basic three operations: apply for read lock, apply for write lock, unlock. Do not implement initialization, trylock, destroy locks, etc. Typedef struct 2. {

3. pthread_mutex_t rw_mutex; //Provide exclusive access to the entire structure

4. pthread_cond_t rw_condreaders;//Used to notify the thread requesting the read lock

5. pthread_cond_t rw_condwriters;//is used to notify the thread to apply for write lock

6. int rw_waitreaders; //waiting for the number of threads to apply for lock lock

7. int rw_waitwriters; //Number of threads waiting to apply for write lock

8. int rw_refcount; //indicates the state of the read-write lock, if it is -1 indicates that it is a write lock

9. }pthread_rwlock_t; //0 indicates that it is available, greater than 0 indicates the number of read locks currently held

10.

11.

12. int pthread_rwlock_rdlock(pthread_rwlock_t *rw) //Apply for a read lock 13. {

14. int result; //Return value (error status) 15.

16. pthread_mutex_lock(&rw->rw_mutex);

17. //When the write lock is in use, the lock cannot be read. When the lock is available but there is a thread waiting to apply for a write lock, the lock cannot be read. This is reflected in the “Writer Priority”. Rw->rw_refcount<0

Copyright © Windows knowledge All Rights Reserved