Subj : Re: when should use mutex/semaphore To : comp.programming.threads From : David Butenhof Date : Wed Jan 12 2005 05:35 pm sachin_mzn@yahoo.com wrote: > > Sometimes I am confused about usage of mutex and semaphore. > When we should use one. Is mutex is best suitable for threads and > semaphore for process. The best (though perhaps not the most easily applied) advice is to use the synchronization primitive that best fits your need. ;-) > What is diffrence between binary semaphore and mutex? A mutex is a binary semaphore with some additional consistency state. To put the distinction in simple terms, a binary semaphore is "locked" or "unlocked", while a mutex is "owned" or "released". When a binary semaphore is "locked", you can unlock from any code path in any thread; there's no consistency checks. When a mutex is "owned", only the thread that owns it can release it. In many implementations, a mutex really is just a binary semaphore, and the code doesn't detect or enforce ownership violations. But tracking ownership provides the ability to, for example, return EDEADLK when a thread attempts to lock a mutex it already owns instead of blocking indefinitely. The consistency checks also protect against code errors such as skipping a lock operation on some path, which can lead to a thread accidentally unlocking a mutex that's already owned by another thread. > When should we use counting semaphore? When you have a counted resource, such that you're writing synchronization code that reads essentially "lock, increment, unlock" and "lock, decrease, unlock", you may be better off with a counting semaphore that does all this in one operation; especially if you're waiting at a boundary condition. For example, if you have a fixed queue of 10 entries that one thread produces for another thread to consume, a counting semaphore with an initial value of 10 might be just what you want. > Is there any good book/tutorial on > multithreading/semaphore/mutex/condition variable available online? Lots of tutorials online, some of them are OK but limited in scope (often setting the stage for a particular class project), while others are out of date, poorly structured, or outright incorrect. You can search and evaluate; I'm sure Google will be happy to report any number of them you want. There are also several good printed books that you can buy in a store or online. -- Dave Butenhof, David.Butenhof@hp.com HP Utility Pricing software, POSIX thread consultant Manageability Solutions Lab (MSL), Hewlett-Packard Company 110 Spit Brook Road, ZK2/3-Q18, Nashua, NH 03062 .