Mutex Locker utility class to lock/unlock mbed RTOS mutexes. Create and pass a mutex, it locks the mutex then unlocks it when destroyed.

Dependents:   SmartLight HelloThreadsYo

Mutex Locker

This utility class is most useful when you have an activity that needs to be protected by a mutex that has multiple return points.

You would normally do this:

Using standard mutex access

Mutex myMutex;

void do_some_stuff()
{
  myMutex.lock();
  /* Do Stuff */

  if (condition) {
    myMutex.unlock();
    return 0;
  }

  /* Call other method */
  int temp = other_method();  // Temp so can unlock after function returns

  myMutex.unlock();
  return temp;
}

However, it's very easy to miss one of the unlock points which would later freeze the application.

Debugging this kind of error can be very hard.

The same example using MutexLocker:

Using a MutexLocker

Mutex myMutex;

int do_some_stuff()
{
  MutexLocker locker(myMutex);
  /* Do Stuff */

  if (condition) {
    return 0;
  }
  /* Call other method */
  return other_method();
  /* Mutex unlocks itself here */
}

No matter where or how your method returns, the mutex will always be unlocked as the MutexLocker goes out of scope.

Files at this revision

API Documentation at this revision

Comitter:
Tomo2k
Date:
Thu Apr 10 21:59:11 2014 +0000
Child:
1:1a8b1de53954
Commit message:
Simple mutex locker

Changed in this revision

mutexlocker.h Show annotated file Show diff for this revision Revisions of this file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mutexlocker.h	Thu Apr 10 21:59:11 2014 +0000
@@ -0,0 +1,17 @@
+#pragma once
+
+#include "rtos.h"
+
+class MutexLocker
+{
+public:
+    MutexLocker(Mutex &mutex) :
+        m_mutex(&mutex) {
+        m_mutex->lock();
+    }
+    ~MutexLocker() {
+        m_mutex->unlock();
+    }
+private:
+    Mutex *m_mutex;
+};