Note: This tutorial assumes that you have completed the previous tutorials: Thread, Threadable.
(!) Please ask about problems and questions regarding this tutorial on answers.ros.org. Don't forget to include in your question the link to this page, the versions of your OS & ROS, and also add appropriate tags.

Thread Locks

Description: Locking threads to protect shared data

Keywords: ecl threads mutex

Tutorial Level: INTERMEDIATE

Contents

  1. Overview

Overview

The mutex is fairly standard, and on some systems can be more complex, but here the wrapper simply acts as a closed door with the usual lock, trylock and unlock features. The behaviour is also somewhat different depending on the platform.

On posix, the class is set up to run in two modes. When NDEBUG is not defined, it will do exception handling (via ecl's StandardException) for posix errors as well as configuring the mutexes for deadlock checking (see below for example code). Exception handling and deadlock checking are disabled when NDEBUG is defined.

   1 Mutex mutex;
   2 
   3 mutex.lock();     // Locks
   4 // do work here
   5 mutex.unlock();
   6 mutex.trylock();  // Locks
   7 mutex.trylock();  // Fails to lock and returns immediately.
   8 mutex.unlock();
   9 
  10 
  11 mutex.lock();
  12 // mutex.lock();     // The DEADLOCK! Like this, the program will usually halt forever.
  13 
  14 // If NDEBUG is not defined, then on posix systems, you can catch deadlocks like this.
  15 try {
  16     mutex.lock();
  17 } catch ( StandardException &e ) { 
  18     std::cout << e.what() << std::endl;
  19 }   
  20 
  21 // Typical output from a caught deadlock:
  22 // Location : /mnt/froody/work/code/cpp/projects/ecl/modules/core/src/lib/threads/mutex_pos.cpp:57
  23         // Flag     : The object was used incorrectly.
  24         // Detail   : DEADLOCK! The mutex has already been locked by this thread, it now has to wait on itself.
  25 

Wiki: ecl_threads/Tutorials/Thread Locks (last edited 2012-01-30 02:32:50 by DanielStonier)