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.

Committer:
Tomo2k
Date:
Thu Apr 10 22:18:40 2014 +0000
Revision:
3:aab6944f2ed3
Parent:
2:8bf85ca6ccee
Disabled copy and assignment as this would be silly

Who changed what in which revision?

UserRevisionLine numberNew contents of line
Tomo2k 2:8bf85ca6ccee 1 /* (C) 2014 Richard Thompson (Tomo2k)
Tomo2k 2:8bf85ca6ccee 2 This software is Apache 2.0 licenced for this to be reused.
Tomo2k 2:8bf85ca6ccee 3
Tomo2k 2:8bf85ca6ccee 4 That said, it's trivial and rather obvious!
Tomo2k 2:8bf85ca6ccee 5 */
Tomo2k 0:0714ae633eab 6 #pragma once
Tomo2k 0:0714ae633eab 7
Tomo2k 0:0714ae633eab 8 #include "rtos.h"
Tomo2k 0:0714ae633eab 9
Tomo2k 1:1a8b1de53954 10
Tomo2k 2:8bf85ca6ccee 11 //! Lock/Unlock Mutex using variable scope.
Tomo2k 1:1a8b1de53954 12 //! Ensures always unlocked regardless of method exit
Tomo2k 0:0714ae633eab 13 class MutexLocker
Tomo2k 0:0714ae633eab 14 {
Tomo2k 0:0714ae633eab 15 public:
Tomo2k 1:1a8b1de53954 16 //! Lock the mutex
Tomo2k 0:0714ae633eab 17 MutexLocker(Mutex &mutex) :
Tomo2k 1:1a8b1de53954 18 m_mutex(mutex) {
Tomo2k 1:1a8b1de53954 19 m_mutex.lock();
Tomo2k 0:0714ae633eab 20 }
Tomo2k 1:1a8b1de53954 21 //! Unlocks on destruction
Tomo2k 0:0714ae633eab 22 ~MutexLocker() {
Tomo2k 1:1a8b1de53954 23 m_mutex.unlock();
Tomo2k 0:0714ae633eab 24 }
Tomo2k 0:0714ae633eab 25 private:
Tomo2k 1:1a8b1de53954 26 Mutex &m_mutex;
Tomo2k 3:aab6944f2ed3 27 // Disable copy
Tomo2k 3:aab6944f2ed3 28 MutexLocker & operator=(const MutexLocker&);
Tomo2k 3:aab6944f2ed3 29 MutexLocker(const MutexLocker &);
Tomo2k 0:0714ae633eab 30 };