As the mutex in most of the systems are implemented using CAS ops, I was wondering about performance comparison of these two constructs.
Is it fair to say that if a mutex is implemented using CAS, then the try-lock call on that mutex will be same/similar performance compare to CAS operations ?
CAS, being highly system dependent, I was thinking if it could be summarily replaced with the more well-known/standardized derivation of it, mutex try-lock.
A lock allows only one thread to enter the part that's locked and the lock is not shared with any other processes. A mutex is the same as a lock but it can be system wide (shared by multiple processes).
lock blocks and only returns when it has the lock, trylock returns immediately and can either succeed or fail to obtain the lock.
Binary semaphores support operations like wait and signal (acquire and release in the case of Java's Semaphore class) to allow modification of the available permits by any process. On the other hand, only the same thread that locked/unlocked a resource can modify a reentrant lock.
Mutex: Use a mutex when you (thread) want to execute code that should not be executed by any other thread at the same time.
Your reasoning is sound; on any sane implementation, the cost of a "trylock" operation will be roughly the same as a CAS. However, CAS in general cannot be replaced by trylock; trylock is a weaker primitive that can't manipulate arbitrary data.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With