Thursday, August 16, 2007

C++Threading

OpenThreads as part of OpenSceneGraph contains a number of nice classes for working with threads in C++, using a Posix implemention (*n*x), or the Win32 or Solaris specific one. It is also possible to compile just the three classes that the threading stuff is comprised of, combine it with the appropriate headers, and use it. One thing is missing, though ... an implementation of the "resource acqusition by constructing" pattern. As C++ does not have a "finally" construct, the best solution to ensure a used mutex is freed in all circumstances (earlier return, exceptions, SEGV, ...) is to create a class that locks the mutex on construction and frees it on destruction, and to instantiate this class when needing the mutex (on the stack, of course, not with new).

class  LockIt {
public:
  LockIt(Mutex& mutex) : mMutex(mutex) { mMutex.lock(); }
  virtual ~LockIt() { mMutex.unlock(); }
private:
  Mutex& mMutex;
};
A Mutex called mMutex is defined somewhere; then, you can use it
{
LockIt(mMutex);
// work locked
}
// lock on mMutex automatically released
The thread helpers that are part of the boost class library are far more powerful in this direction, they also contain various lock acquisition classes. Boost will also be part of the next release of the C++ standard ... on the other hand, it is really large (a thousand header files, if I counted right), and not that easy to use ...

No comments: