summaryrefslogtreecommitdiff
path: root/src/unstable/readwritemutex.cpp
diff options
context:
space:
mode:
authorMike Buland <eichlan@xagasoft.com>2013-02-21 03:55:56 +0000
committerMike Buland <eichlan@xagasoft.com>2013-02-21 03:55:56 +0000
commit9dd51c94844bc7e5f8b1552511d31ed2c9bac05c (patch)
tree3dd505ddea45f47f2a413eba05074a9605afbe6c /src/unstable/readwritemutex.cpp
parent123434f227a963cf26f9637136bf759a824f930a (diff)
downloadlibbu++-9dd51c94844bc7e5f8b1552511d31ed2c9bac05c.tar.gz
libbu++-9dd51c94844bc7e5f8b1552511d31ed2c9bac05c.tar.bz2
libbu++-9dd51c94844bc7e5f8b1552511d31ed2c9bac05c.tar.xz
libbu++-9dd51c94844bc7e5f8b1552511d31ed2c9bac05c.zip
Added the Bu::ReadWriteMutex, which is super awesome. Also made the
Bu::RandomBase::rand functions visible in the Bu::RandomCmwc class.
Diffstat (limited to 'src/unstable/readwritemutex.cpp')
-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}