Qore Programming Language  0.8.7
 All Classes Files Functions Variables Typedefs Enumerations Enumerator Macros Groups Pages
QoreRWLock.h
1 /* -*- mode: c++; indent-tabs-mode: nil -*- */
2 /*
3  QoreRWLock.cc
4 
5  simple pthreads-based read-write lock
6 
7  Qore Programming Language
8 
9  Copyright 2003 - 2013 David Nichols
10 
11  This library is free software; you can redistribute it and/or
12  modify it under the terms of the GNU Lesser General Public
13  License as published by the Free Software Foundation; either
14  version 2.1 of the License, or (at your option) any later version.
15 
16  This library is distributed in the hope that it will be useful,
17  but WITHOUT ANY WARRANTY; without even the implied warranty of
18  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19  Lesser General Public License for more details.
20 
21  You should have received a copy of the GNU Lesser General Public
22  License along with this library; if not, write to the Free Software
23  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
24 */
25 
26 #ifndef _QORE_QORERWLOCK_H
27 #define _QORE_QORERWLOCK_H
28 
29 #include <pthread.h>
30 
32 
35 class QoreRWLock {
36 protected:
38  pthread_rwlock_t m;
39 
41  DLLLOCAL QoreRWLock& operator=(const QoreRWLock&);
42 
43 public:
45  DLLLOCAL QoreRWLock() {
46 #ifndef NDEBUG
47  int rc =
48 #endif
49  pthread_rwlock_init(&m, 0);
50  assert(!rc);
51  }
52 
54  DLLLOCAL ~QoreRWLock() {
55 #ifndef NDEBUG
56  int rc =
57 #endif
58  pthread_rwlock_destroy(&m);
59  assert(!rc);
60  }
61 
63  DLLLOCAL int rdlock() {
64  return pthread_rwlock_rdlock(&m);
65  }
66 
68  DLLLOCAL int wrlock() {
69  return pthread_rwlock_wrlock(&m);
70  }
71 
73  DLLLOCAL int tryrdlock() {
74  return pthread_rwlock_tryrdlock(&m);
75  }
76 
78  DLLLOCAL int trywrlock() {
79  return pthread_rwlock_trywrlock(&m);
80  }
81 
83  DLLLOCAL int unlock() {
84  return pthread_rwlock_unlock(&m);
85  }
86 };
87 
89 
94 private:
97 
99  DLLLOCAL QoreAutoRWReadLocker& operator=(const QoreAutoRWReadLocker&);
100 
102  DLLLOCAL void *operator new(size_t);
103 
104 protected:
107 
108 public:
110  DLLLOCAL QoreAutoRWReadLocker(QoreRWLock &n_l) : l(&n_l) {
111  l->rdlock();
112  }
113 
115  DLLLOCAL QoreAutoRWReadLocker(QoreRWLock *n_l) : l(n_l) {
116  l->rdlock();
117  }
118 
121  l->unlock();
122  }
123 };
124 
126 
131 private:
134 
136  DLLLOCAL QoreAutoRWWriteLocker& operator=(const QoreAutoRWWriteLocker&);
137 
139  DLLLOCAL void *operator new(size_t);
140 
141 protected:
144 
145 public:
147  DLLLOCAL QoreAutoRWWriteLocker(QoreRWLock &n_l) : l(&n_l) {
148  l->wrlock();
149  }
150 
152  DLLLOCAL QoreAutoRWWriteLocker(QoreRWLock *n_l) : l(n_l) {
153  l->wrlock();
154  }
155 
158  l->unlock();
159  }
160 };
161 
162 #endif // #ifndef _QORE_QORERWLOCK_H