Reputation: 2527
if I have a method like this:
def getValue()
{
lock.acquire();
int result = data[index];
lock.release();
return result;
}
Two threads can reach lock.acquire() at the exact same time. What happens then?
Upvotes: 5
Views: 4575
Reputation: 8268
In practice locks must be implemented in term of an operation atomic at the CPU level: if lock_state is FREE then set lock_state to LOCKED else jump lock_failed
Observing lock_state
equal to FREE
and setting it to LOCKED
must be atomic with respect to other threads on the same CPU and those on other CPU, so some kind of locking of memory access between CPU is involved. One way to do that is through the cache system: one CPU sets a memory range including the manipulated value to "owned exclusively" so others CPU can't even try to access that range of bytes until that CPU is done with the operation. (These owning states are needed for cache consistency no matter what. There is no additional inter CPU complexity involved.)
So it all comes down to which CPU gets to first "own exclusively" the memory range which includes lock_state
when lock_state
has value FREE
.
When locking fails, a much more complicated process is involved to make sure the thread that tries to lock it can be paused and restarted as soon as the lock is free again. The details are extremely system dependent.
Upvotes: 3
Reputation: 182761
One of them gets the lock first and the other must wait until the first one releases the lock. If they reach acquire at the exact same time, the mechanism that decides which one gets the lock is heavily hardware dependent.
I should point out though that there is no such thing as "at the exact same time". To have two things that occur in different threads happen at the exact same time would require there to be some global notion of time in which operations are ordered. There is no such thing.
Also, the concept of when a thread will "reach" an operation also isn't well defined. Operations don't take place instantaneously and operations can overlap with other operations.
Upvotes: 7