views:

118

answers:

3

This is a lock that can be held by only one thread of execution at a time. An attempt to acquire the lock by another thread of execution makes the latter loop until the lock is released.

How does it handle the case when two threads try to acquire the lock exactly the same time?

I think this question also applies to various of other mutex implementation.

A: 

Depends on the processor and the threading implementation. Most processors have instructions that can be executed atomically, on top of which you can build things like spin locks. For example IA-32 has an xchg instruction that does an atomic swap. You can then implement a naive spinlock like:

  eax = 1;
  while( xchg(eax, lock_address) != 0 );
  // now I have the lock
  ... code ...
  *lock_address = 0; // release the lock
Logan Capaldo
This doesn't explain away how the **multiple** processor will deal with two **concurrent** acquire.
httpinterpret
Again, it depends on the processor architecture. Implementation of `xchg` is a microcode/hardware problem. Ultimately, nothing actually happens at exactly the same time, even with multiple processors/cores they share a bus and a clock. It should be possible to find the control path for one of these instructions for a specific processor (SPARC might be the easiest), but there is unlikely to be a specific answer that applies in general.
Logan Capaldo
So lock is ultimately implemented based on the fact that nothing actually happens at exactly the same time ?
httpinterpret
Saying "nothing actually happens at exactly the same time" is in some sense an overstatement on my part. Rather, there are some things that can't happen at the same time as themselves. One example might be, say you have a machine with 32 bits of memory. Two processors can't simultaneously flip bit 0, there's only one logical line leading into that bit (flip-flop or whatever). On top of these properties things like `xchg` get built, and on top of things like `xchg`, spinlocks, mutexes etc. get built.
Logan Capaldo
A: 

http://en.wikipedia.org/wiki/Spinlock

Adal
Given that SO strives to be a repository of *information* and not just links, you should write at *least* the gist of what it says at the other end of that link...
dmckee
+1  A: 
pgod