Mutex

A mutex is a key concept in multi-threaded programs. Under windows they are called “critical sections” which is the same as a mutex under POSIX style operating systems.

Mutexes are used to protect parts of an application that would be corrupted if multiple threads were to go through them at the same time.

For instance if you have a class with a string data member a corruption could occur if two threads tried to write to it at the same time. A mutex will protect this data member by locking out additional threads until the first thread has gone through.

In our core library we have wrappers for mutexes that work on Windows, Mac OS X and Linux. This wrapper is called COLmutex:

class Foo{ COLmutex Mutex; COLstring Name; void setName(const char* NewName) { Mutex.lock(); // only one threads can go through now Name = NewName; Mutex.unlock(); // now other threads are allowed to enter } };

The mutex prevents any additional threads from going through. However there is a problem with the above code. If an exception is thrown before the unlock() call is invoked then the mutex is never released – hence a thread lock condition could occur. For this reason the COL library has a COLlocker object which locks the mutex in its constructor and always unlocks it in its destructor. i.e.

void Foo::setName(const char* NewName) { COLlocker Locker(Mutex); // we lock the mutex Name = NewName; // as we exit the method, the Locker object goes out of scope // and is automatically destructed - therefore it calls unlock() // on the mutex automatically // even if an exception is thrown in the method - hence no chance // of thread locks occurring }

You should always use COLlocker rather than calling the lock() and unlock() methods directly.

Generally speaking unless you are using COLmutex to build some library code, application code shouldn’t be using this class directly. See share nothing.