Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a mutex is not acquired?

Tags:

c

mutex

pthreads

I want to check if the mutex is free and not acquired.

I tried to use pthread_mutex_trylock(mutex_object);

But that return a 0 if mutex is acquired and -1 for error.

What if the mutex is not acquired? Does it return any value for it?

like image 736
satej k Avatar asked Oct 08 '14 14:10

satej k


People also ask

Can you check if a mutex is locked?

Although you can Lock() or Unlock() a mutex, you can't check whether it's locked.

What happens if a mutex is already locked?

If the mutex is already locked by another thread, the thread waits for the mutex to become available. The thread that has locked a mutex becomes its current owner and remains the owner until the same thread has unlocked it.

What happens if mutex is not released?

If the mutex is already locked, the calling thread shall block until the mutex becomes available. This operation shall return with the mutex object referenced by mutex in the locked state with the calling thread as its owner.

How do you detect a mutex deadlock?

Using pthread_mutex_lock() and pthread_mutex_unlock() Mutex locks are acquired and released. If a thread try to acquire a locked mutex, the call to pthread_mutex_lock() blocks the thread until the owner of the mutex lock invokes pthread_mutex_unlock().


1 Answers

pthread_mutex_trylock does not return "-1 for error". It returns an 'error' code from the possible values in errno.h. One of these, EBUSY, means that another thread already owns the lock. You should not observe any other error codes from pthread_mutex_trylock unless you have serious bugs in your program.

Note that for recursive mutexes, a return value of 0 does not distinguish between the case where the mutex was previously unlocked, and the case where the calling thread already owned it. In any case, if pthread_mutex_trylock returns 0, you're responsible for unlocking it via pthread_mutex_unlock since you become the owner (or, in the recursive case, your lock count increases by 1) on successful pthread_mutex_trylock.

like image 123
R.. GitHub STOP HELPING ICE Avatar answered Oct 20 '22 13:10

R.. GitHub STOP HELPING ICE