aboutsummaryrefslogtreecommitdiff
path: root/src/unstable/readwritemutex.cpp
diff options
context:
space:
mode:
Diffstat (limited to '')
-rw-r--r--src/unstable/readwritemutex.cpp78
1 files changed, 78 insertions, 0 deletions
diff --git a/src/unstable/readwritemutex.cpp b/src/unstable/readwritemutex.cpp
new file mode 100644
index 0000000..b0a3b77
--- /dev/null
+++ b/src/unstable/readwritemutex.cpp
@@ -0,0 +1,78 @@
1#include "bu/readwritemutex.h"
2
3Bu::ReadWriteMutex::ReadWriteMutex() :
4 iCounter( 0 ),
5 bWantWrite( false )
6{
7}
8
9Bu::ReadWriteMutex::~ReadWriteMutex()
10{
11}
12
13void Bu::ReadWriteMutex::lockRead()
14{
15 // Check to see if someone wants to write
16 cWrite.lock();
17 if( bWantWrite )
18 {
19 // If so, wait patiently for them to finish
20 cWrite.wait();
21 }
22 cWrite.unlock();
23
24 // Now lock the read counter
25 mRead.lock();
26 iCounter++;
27 // If the lock counter is one, we just locked for the first time,
28 // so we lock the writer.
29 if( iCounter == 1 )
30 mWrite.lock();
31 mRead.unlock();
32}
33
34void Bu::ReadWriteMutex::unlockRead()
35{
36 // Lock the read counter
37 mRead.lock();
38 iCounter--;
39 // If we just decremented the counter back to zero then we can
40 // release the write lock
41 if( iCounter == 0 )
42 mWrite.unlock();
43 mRead.unlock();
44}
45
46void Bu::ReadWriteMutex::lockWrite()
47{
48 // Lock the read counter
49 mRead.lock();
50 if( iCounter > 0 )
51 {
52 // If there is an active read in progress then we set the bWantWrite
53 // flag to make sure no more readers start working.
54 cWrite.lock();
55 bWantWrite = true;
56 cWrite.unlock();
57 }
58 mRead.unlock();
59
60 // Lock the write lock
61 mWrite.lock();
62}
63
64void Bu::ReadWriteMutex::unlockWrite()
65{
66 // Just always set the bWantWrite flag to false at this point, as long
67 // as we're locked.
68 cWrite.lock();
69 bWantWrite = false;
70 cWrite.unlock();
71
72 // Release all waiting readers, they won't actually do much until we
73 // unlock the write lock though
74 cWrite.broadcast();
75
76 // Unlock the write lock
77 mWrite.unlock();
78}