Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

try-lock mutex call vs CAS calls

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.

like image 858
Ajeet Ganga Avatar asked Sep 08 '11 14:09

Ajeet Ganga


People also ask

What is the difference between a mutex and a 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).

What is the difference between lock and Trylock?

lock blocks and only returns when it has the lock, trylock returns immediately and can either succeed or fail to obtain the lock.

Why are semaphores better than locks?

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.

When would you use a mutex 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.


1 Answers

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.

like image 176
R.. GitHub STOP HELPING ICE Avatar answered Oct 09 '22 14:10

R.. GitHub STOP HELPING ICE