Subj : Re: Diff b/w Events, Semaphores and mutex To : comp.programming.threads From : Eric Sosman Date : Tue Apr 26 2005 11:11 am Gurikar wrote: > Thank you david, > Mutex: A lock that only one thread can hold. These are used to ensure > > that only a single thread accesses a shared object at a time. > > Mutex can only lock shared object but not particluar piece of code. > Is it? Think of the baton in a relay race at a track meet. Each team has one baton, and the rules state that a racer may not run on the track unless he holds his team's baton. There is no physical association between the baton and his team's lane on the track -- the racer is physically capable of running whenever he feels like it -- but the conventions of the race require that he run only while holding the baton. A mutex is like the baton: It is a token signifying that its holder can use the shared resource. There is no physical connection between the mutex and the resource, just as there is no physical connection between the baton and the lane. The code could use the shared resource without holding the mutex, just as the racer could run along the track without holding the baton. The association between code/racer, resource/track, and mutex/baton is a matter of program convention/race rules. (This analogy is fairly good, but not perfect. For example, the act of locking or unlocking a mutex has effects on the "visibility" of changes made to memory; I can think of no corresponding effect in the exchange of the baton. Also, as the racers exchange the baton there is a short time while both are holding it; this doesn't happen with mutexes. The point of the analogy, though, is that the mutex' association with the "protected" resource is purely conventional.) > Semaphores: A number. You can increase the number, decrease the number, > > or do a "wait and decrement" operation. They can be used to ensure that > no > more than a particular number of threads (which can be one) can access > a > particular resource. > > What do you mean particluar resource, is it a object or piece of > object. Yes. As with a mutex, the nature of what is "protected" is entirely up to the program. When you design the program, you decide what needs to be protected and how finely to divide the protected parts. One program may use a single lock to guard an entire data structure, while another may use separate locks to guard individual pieces of it. It all depends on the needs of the program. -- Eric.Sosman@sun.com .