1
// ---------------------------------------------------------------------------
3
// - standard object library - read-write lock class implementation -
4
// ---------------------------------------------------------------------------
5
// - This program is free software; you can redistribute it and/or modify -
6
// - it provided that this copyright notice is kept intact. -
8
// - This program is distributed in the hope that it will be useful, but -
9
// - without any warranty; without even the implied warranty of -
10
// - merchantability or fitness for a particular purpose. In no event shall -
11
// - the copyright holder be liable for any direct, indirect, incidental or -
12
// - special damages arising in any way out of the use of this software. -
13
// ---------------------------------------------------------------------------
14
// - copyright (c) 1999-2007 amaury darsch -
15
// ---------------------------------------------------------------------------
18
#include "Exception.hpp"
23
// -------------------------------------------------------------------------
25
// -------------------------------------------------------------------------
27
// create a new read-write lock
29
Lockrw::Lockrw (void) {
31
p_mtx = c_mtxcreate ();
33
throw Exception ("lockrw-error", "cannot create read-write lock");
34
p_rcv = c_tcvcreate ();
37
throw Exception ("lockrw-error", "cannot create read-write lock");
39
p_wcv = c_tcvcreate ();
43
throw Exception ("lockrw-error", "cannot create read-write lock");
51
// destroy this read-write lock
53
Lockrw::~Lockrw (void) {
59
// lock this read-write lock for reading
61
void Lockrw::rdlock (void) {
65
// check if we have the write lock
66
if ((d_wcount > 0) && (c_threqual (p_tid) == true)) {
72
// wait until the writers have finished
73
while (d_wcount > 0) {
75
c_tcvwait (p_rcv, p_mtx);
79
// here we have a new reader
84
// lock this read-write lock for writing
86
void Lockrw::wrlock (void) {
90
// check if we have already the lock
91
if ((d_wcount > 0) && (c_threqual (p_tid) == true)) {
97
// check if we have some readers or writers
98
while ((d_rcount > 0) || (d_wcount > 0)) {
100
c_tcvwait (p_wcv, p_mtx);
103
// here we have a new write lock
105
p_tid = c_thrself ();
109
// unlock a read-write lock
111
void Lockrw::unlock (void) {
115
// adjust the counters - we can only have one writer - for recursive
116
// writer, we simply decrement the counter
124
} else if (d_rcount > 0) d_rcount--;
126
// give preference to waiting writers
129
} else if (d_waitrd > 0) {