1 Reader Writer Locks pseudocode
2 ==============================
4 pthread_rwlock_rdlock(pthread_rwlock_t *rwlock);
5 pthread_rwlock_unlock(pthread_rwlock_t *rwlock);
6 pthread_rwlock_wrlock(pthread_rwlock_t *rwlock);
8 struct pthread_rwlock_t {
13 unsigned int writers_preferred;
14 - locking mode: 0 recursive, readers preferred
15 1 nonrecursive, writers preferred
18 - number of read-only references various threads have
21 - descriptor of the writer or 0
23 unsigned int readers_wakeup;
24 - 'all readers should wake up' futex.
26 unsigned int writer_wakeup;
27 - 'one writer should wake up' futex.
29 unsigned int nr_readers_queued;
30 - number of readers queued up.
32 unsigned int nr_writers_queued;
33 - number of writers queued up.
36 pthread_rwlock_rdlock(pthread_rwlock_t *rwlock)
38 lll_lock(rwlock->lock);
40 if (!rwlock->writer && (!rwlock->nr_writers_queued ||
41 !rwlock->writers_preferred))
44 rwlock->nr_readers_queued++;
45 lll_unlock(rwlock->lock);
47 futex_wait(&rwlock->readers_wakeup, 0)
49 lll_lock(rwlock->lock);
50 if (!--rwlock->nr_readers_queued)
51 rwlock->readers_wakeup = 0;
54 lll_unlock(rwlock->lock);
57 pthread_rwlock_tryrdlock(pthread_rwlock_t *rwlock)
60 lll_lock(rwlock->lock);
61 if (!rwlock->writer && (!rwlock->nr_writers_queued ||
62 !rwlock->writers_preferred))
64 lll_unlock(rwlock->lock);
68 pthread_rwlock_wrlock(pthread_rwlock_t *rwlock)
70 lll_lock(rwlock->lock);
72 if (!rwlock->writer && !rwlock->readers)
75 rwlock->nr_writers_queued++;
76 lll_unlock(rwlock->lock);
78 futex_wait(&rwlock->writer_wakeup, 0);
80 lll_lock(rwlock->lock);
81 rwlock->nr_writers_queued--;
82 rwlock->writer_wakeup = 0;
84 rwlock->writer = pthread_self();
85 lll_unlock(rwlock->lock);
88 pthread_rwlock_unlock(pthread_rwlock_t *rwlock)
90 lll_lock(rwlock->lock);
97 if (!rwlock->readers) {
98 if (rwlock->nr_writers_queued) {
99 rwlock->writer_wakeup = 1;
100 futex_wake(&rwlock->writer_wakeup, 1);
102 if (rwlock->nr_readers_queued) {
103 rwlock->readers_wakeup = 1;
104 futex_wake(&rwlock->readers_wakeup, MAX_INT);
108 lll_unlock(rwlock->lock);