2 ** This basic implementation of Reader/Writer locks does not
3 ** protect writers from starvation. That is, if a writer is
4 ** currently waiting on a reader, any new reader will get
5 ** the lock before the writer.
8 /********************************************************
9 * An example source module to accompany...
11 * "Using POSIX Threads: Programming with Pthreads"
12 * by Brad nichols, Dick Buttlar, Jackie Farrell
13 * O'Reilly & Associates, Inc.
15 ********************************************************
18 * Library of functions implementing reader/writer locks
21 #define DISABLE_BRIDGE
26 #include <lthread_rdwr.h>
28 int pthread_rdwr_init_np(pthread_rdwr_t *rdwrp, pthread_rdwrattr_t *attrp)
30 rdwrp->readers_reading = 0;
31 rdwrp->writer_writing = 0;
32 pthread_mutex_init(&(rdwrp->mutex), NULL);
33 pthread_cond_init(&(rdwrp->lock_free), NULL);
37 int pthread_rdwr_rlock_np(pthread_rdwr_t *rdwrp){
38 pthread_mutex_lock(&(rdwrp->mutex));
39 while(rdwrp->writer_writing) {
40 pthread_cond_wait(&(rdwrp->lock_free), &(rdwrp->mutex));
42 rdwrp->readers_reading++;
43 pthread_mutex_unlock(&(rdwrp->mutex));
47 int pthread_rdwr_runlock_np(pthread_rdwr_t *rdwrp)
49 pthread_mutex_lock(&(rdwrp->mutex));
50 if (rdwrp->readers_reading == 0) {
51 pthread_mutex_unlock(&(rdwrp->mutex));
55 rdwrp->readers_reading--;
56 if (rdwrp->readers_reading == 0) {
57 pthread_cond_signal(&(rdwrp->lock_free));
59 pthread_mutex_unlock(&(rdwrp->mutex));
64 int pthread_rdwr_wlock_np(pthread_rdwr_t *rdwrp)
66 pthread_mutex_lock(&(rdwrp->mutex));
67 while(rdwrp->writer_writing || rdwrp->readers_reading) {
68 pthread_cond_wait(&(rdwrp->lock_free), &(rdwrp->mutex));
70 rdwrp->writer_writing++;
71 pthread_mutex_unlock(&(rdwrp->mutex));
75 int pthread_rdwr_wunlock_np(pthread_rdwr_t *rdwrp)
77 pthread_mutex_lock(&(rdwrp->mutex));
78 if (rdwrp->writer_writing == 0) {
79 pthread_mutex_unlock(&(rdwrp->mutex));
83 rdwrp->writer_writing = 0;
84 pthread_cond_broadcast(&(rdwrp->lock_free));
85 pthread_mutex_unlock(&(rdwrp->mutex));
93 * return 0 if false, suitable for assert(pthread_rdwr_Xchk(rdwr))
95 * Currently they don't check if the calling thread is the one
96 * that has the lock, just that there is a reader or writer.
98 * Basically sufficent for testing that places that should have
102 int pthread_rdwr_rchk_np(pthread_rdwr_t *rdwrp)
104 return(rdwrp->readers_reading!=0);
107 int pthread_rdwr_wchk_np(pthread_rdwr_t *rdwrp)
109 return(rdwrp->writer_writing!=0);
111 int pthread_rdwr_rwchk_np(pthread_rdwr_t *rdwrp)
113 return(pthread_rdwr_rchk_np(rdwrp) || pthread_rdwr_wchk_np(rdwrp));
116 #endif /* LDAP_DEBUG */