1 /*
2  *  This code is from the book "Programming with POSIX Threads", by
3  *  David R. Butenhof. Appears in modified and GPL'ed form in at least
4  *  the Bacula sources.
5  */
6 
7 #ifndef RWLOCK_H
8 #define RWLOCK_H
9 
10 /*
11  * rwlock.h
12  *
13  * This header file describes the "reader/writer lock" synchronization
14  * construct. The type rwlock_t describes the full state of the lock
15  * including the POSIX 1003.1c synchronization objects necessary.
16  *
17  * A reader/writer lock allows a thread to lock shared data either for shared
18  * read access or exclusive write access.
19  *
20  * The rwl_init() and rwl_destroy() functions, respectively, allow you to
21  * initialize/create and destroy/free the reader/writer lock.
22  */
23 
24 #include <pthread.h>
25 
26 #ifdef PTHREAD_RWLOCK_INITIALIZER
27 // #ifdef HAVE_PTHREAD_RWLOCK
28 
29 #define rwlock_t pthread_rwlock_t
30 
31 #define RWL_INITIALIZER PTHREAD_RWLOCK_INITIALIZER
32 
33 #define rwl_init(tag) pthread_rwlock_init(tag, NULL)
34 #define rwl_destroy pthread_rwlock_destroy
35 #define rwl_rdlock pthread_rwlock_rdlock
36 #define rwl_tryrdlock pthread_rwlock_tryrdlock
37 #define rwl_rdunlock pthread_rwlock_unlock
38 #define rwl_wrlock pthread_rwlock_wrlock
39 #define rwl_trywrlock pthread_rwlock_trywrlock
40 #define rwl_wrunlock pthread_rwlock_unlock
41 
42 #else /* HAVE_PTHREAD_RWLOCK */
43 
44 /*
45  * Structure describing a read-write lock.
46  */
47 typedef struct rwlock_tag {
48     pthread_mutex_t     mutex;
49     pthread_cond_t      read;           /* wait for read */
50     pthread_cond_t      write;          /* wait for write */
51     int                 valid;          /* set when valid */
52     int                 r_active;       /* readers active */
53     int                 w_active;       /* writer active */
54     int                 r_wait;         /* readers waiting */
55     int                 w_wait;         /* writers waiting */
56 } rwlock_t;
57 
58 #define RWLOCK_VALID    0xfacade
59 
60 /*
61  * Support static initialization of read-write locks.
62  */
63 #define RWL_INITIALIZER \
64     {PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER, \
65     PTHREAD_COND_INITIALIZER, RWLOCK_VALID, 0, 0, 0, 0}
66 
67 /*
68  * Define read-write lock functions
69  */
70 extern int rwl_init (rwlock_t *rwlock);
71 extern int rwl_destroy (rwlock_t *rwlock);
72 extern int rwl_rdlock (rwlock_t *rwlock);
73 extern int rwl_tryrdlock (rwlock_t *rwlock);
74 extern int rwl_rdunlock (rwlock_t *rwlock);
75 extern int rwl_wrlock (rwlock_t *rwlock);
76 extern int rwl_trywrlock (rwlock_t *rwlock);
77 extern int rwl_wrunlock (rwlock_t *rwlock);
78 
79 #endif  /* not HAVE_POSIX_RWLOCK */
80 
81 #endif /* RWLOCK_H */
82 
83