From 9dd51c94844bc7e5f8b1552511d31ed2c9bac05c Mon Sep 17 00:00:00 2001 From: Mike Buland Date: Thu, 21 Feb 2013 03:55:56 +0000 Subject: Added the Bu::ReadWriteMutex, which is super awesome. Also made the Bu::RandomBase::rand functions visible in the Bu::RandomCmwc class. --- src/unstable/readwritemutex.h | 75 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 src/unstable/readwritemutex.h (limited to 'src/unstable/readwritemutex.h') diff --git a/src/unstable/readwritemutex.h b/src/unstable/readwritemutex.h new file mode 100644 index 0000000..9e07047 --- /dev/null +++ b/src/unstable/readwritemutex.h @@ -0,0 +1,75 @@ +#ifndef BU_READ_WRITE_MUTEX_H +#define BU_READ_WRITE_MUTEX_H + +#include "bu/mutex.h" +#include "bu/condition.h" + +namespace Bu +{ + /** + * Mutex designed for situations where overlapped reading is safe, but + * overlapped writing isn't. There are many, many good examples of this + * including most data structures, streams, etc. etc. + * + * Use this just like a normal mutex except that you use the + * lockRead/unlockRead and lockWrite/unlockWrite functions depending on + * weather the section of code your locking is reading data or changing + * data. + * + * This particular mutex is designed so that while a read operation is + * happening other read operations can also happen, but no write operations + * can occur. While a write is happening, no other write or read operation + * can continue. There is an extra feature to ensure writes get a chance + * to complete, when a lockWrite is issued, all current read operations + * continue, but future read operations block until the write is complete. + */ + class ReadWriteMutex + { + public: + ReadWriteMutex(); + virtual ~ReadWriteMutex(); + + /** + * Lock the mutex for reading. Multiple code sections can hold a read + * lock at the same time, but write locks will wait for all read locks + * to be released before continuing. Read locks will also wait if + * there is an active write lock. + * + * It is very important to not make any changes to your data within + * a read lock. + */ + void lockRead(); + + /** + * Release a read lock. + */ + void unlockRead(); + + /** + * Lock the mutex for writing. Only one code section can have a write + * lock at any given time. No code sections can be in a locked read + * section while a write lock is held. When a write lock is requested + * all following read locks will block until the write operation is + * started, ensuring writes always get a chance to execute. + * + * Within a write locked code section feel free to change your data + * and read your data. It is imparative to spend as little time as + * possible in a write-locked section. + */ + void lockWrite(); + + /** + * Release a write lock. + */ + void unlockWrite(); + + private: + Bu::Mutex mRead; + int iCounter; + Bu::Mutex mWrite; + Bu::Condition cWrite; + bool bWantWrite; + }; +}; + +#endif -- cgit v1.2.3