Image

Imagekenshinhimura wrote in Imagecpp

Mutual Exclusion, Multithreading, Exceptions & C++

This is a technique that was new to me and I thought I'd share it with you guys. I saw this from a code segment from the Modern C++ Design book, its a shame not many C++ books address multithreading techniques and issues (probably because C++ is not a natively multithreading language).

Consider the following code:

class Lock {
public:
    Lock() {
        // obtain the mutex (platform dependent)
    }

    ~Lock() {
        // release the mutex
    }
};

void functionThatNeedsMutex() 
{
    Lock lock; // invoke the call to mutex

    // operations that need mutex

} 
// Once this function terminates, the destructor 
// automatically gets called, even if the operation 
// that needed the mutex threw an exception.
// Hence the mutex gets released without having a single
// try catch operation... nifty eh?



The equivalent code on Win32 would be something like:

void functionThatNeedsMutex()
{
    // pNamedMutex is a HANDLE declared globally
    WaitForSingleObject( pNamedMutex, INFINITE );

    try {

        // operations that need mutex
    
    } catch( ... ) {
        ReleaseMutex( pNamedMutex );
        throw;
    }

    ReleaseMutex( pNamedMutex );
}


While the two code have similar functionality, the first one did not incur the overhead introduced by the extra exception handling code.

Another advantage would be additional segmentation between code that's platform dependent and those that aren't. Because the only code that knows about the mutex API is the Lock class, all the clients of lock class can be ported to different platforms and all that you need to do is change the implementation for the Lock class.

Oh and not to mention that the first code is much more cleaner than the second code. ;)