What are the differences among mutex, semaphore and read write locks

user2601350 picture user2601350 · Aug 3, 2013 · Viewed 9.8k times · Source

Any real-time scenarios explaining on each would be appreciated. Is there any other way to handle synchronization apart from these in pthreads. How do mutex differ from recursive-mutexes(any real-time scenario)?

Answer

A mutex can be used to protect a shared resource (a variable, a file, a peripheral device) from modifications that could leave it in an inconsistent state.

A semaphore can be used to manage a finite pool of identical shared resources (one important case of this is an IPC queue). Threads can take a resource from the pool, put one to the pool, or wait until one becomes available. Note you may still have to use a mutex in addition to a semaphore (to protect the pool data structure itself).

A read-write lock can be used to protect a shared resource that can be either read or written to (modified). All reader threads can access it simultaneously. A writer thread needs exclusive access.

A conditional variable can be used, together with a mutex, to signal events.

Wikipedia can be used to read about most of this.