Reputation: 13
what happen in the extremely unlucky case that two processes arrive at exactly & precisely the same moment. This is not likely, but probabilistically can happen from time to time. Even more coincidentally, let’s assume the lock is OPEN so that both processes would find the lock available. What happens?
Upvotes: 0
Views: 459
Reputation:
Mutexes implemented using atomic operations. Different processor architectures implement this differently, but regardless of what processor does, on the lower level there is always a bus arbiter hardware that will have to pick correct order for all simultaneous memory accesses.
So even if two processors are accessing the same mutex at exactly the same moment in time, bus arbiter will choose who will be the first one and who will be the second one.
In the end, nothing happens at exactly the same moment in time - everything is ordered.
You may read more about how memory access works at Fixing Gap in knowledge about C/C++ and register access
In short, processor does not access memory directly, instead it asks memory controller to do this. When two processor ask memory device to do something at the same time, it has to pick one of them first.
Upvotes: 1
Reputation: 490098
Locking a mutex is an atomic process, so even if two threads manage to request the mutex at exactly the same time, one of them will succeed and the other will fail--that is to say, one will lock the mutex, and the other won't.
Any other result means the mutex is utterly and irrevocably broken--i.e., it's not really a mutex at all.
Upvotes: 0