Skip to content

mutexes

Thursday, 26 July 2007  |  Zander

If you ever did anything with multithreading you'd know mutexes. They are basically a building block to do any multithreading work in.

In java they are better known as 'synchronized blocks'. Your basic hot zone can be protected by a combination of myMutex.lock(); /* do stuff here*/ myMutex.unlock(); Which is equivalent to the Java manner of synchronized(myMutex) { /* do stuff here */ }

My biggest problem with the mutex method is that if I add a return before the unlock part, I've got a problem. The mutex will never be unlocked. So you will get weird errors that just when that corner case happens which will do such an early return, things will lock up.

So I tend to write the following:

  QMutex lock;
  {
      struct Finalizer {
        Finalizer(QMutex &lock) : l(&lock) { l->lock(); }
        ~Finalizer() { l->unlock(); }
         QMutex *l;
      };
      Finalizer finalizer(lock);
      // foo bar
  }

This means that even if I do a return; call somewhere in that "foo bar" block my lock will nicely be unlocked again.

Now; is there someone that is good with macros and allow me to type the following to expand to the former?

  QMutex lock;
  synchronized(lock) {
     // foo bar
  }

Have fun!