(!) 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.

Semaphores

Description: Locks for multiple processes (use with shared memory).

Keywords: ecl semaphores

Tutorial Level: INTERMEDIATE

Next Tutorial: Shared Memory

There are many ways to implement semaphores (especially the counting semaphores on posix), but I've kept it relatively simple here with the task at hand being just to provide a lock that can be used when accessing shared memory. Its usage is very similar to thread mutexes with the only difference being the instantiation via a string identifier (similar to the case for shared memory). Note, on windows semaphores are usually referred to as mutexes (confusing!).

   1 //...First process
   2 Semaphore semaphore("test_sem");
   3 semaphore.lock();
   4 // ... access shared memory here
   5 semaphore.unlock();
   6 
   7 //...Second process
   8 Semaphore semaphore("test_sem");
   9 semaphore.lock();
  10 // ... access shared memory here
  11 semaphore.unlock();

If another semaphore (doesn't have to be the same object, just a semaphore instantiated from the same name) tries to lock an already locked semaphore, it will wait until the first semaphore releases the lock. Be wary of deadlocks.

Wiki: ecl_ipc/Tutorials/Semaphores (last edited 2012-01-24 23:40:39 by DanielStonier)