C Mutex Values ​​of Pthreads?

I am writing a program with several critical sections. The thing is, I need to check the value of the mutex in the if statement.

I would like to do something like this:

if pthread_mutex(&mutex) == 0 // locked 
  // Do something
else if pthread_mutex(&mutex) == 1 // unlocked 
 // Do something else

Is it possible?

+3
source share
3 answers

You want to pthread_mutex_trylock().

From this link:

pthread_mutex_trylock() pthread_mutex_lock(), , mutex, mutex, ( , ), . ... ... pthread_mutex_trylock() , mutex, mutex. ,

, :

pthread_mutex_t *m = /* ... */;

if (pthread_mutex_trylock(m) == 0)
{
    /* Success!  This thread now owns the lock. */
}
else
{
    /* Fail!  This thread doesn't own the lock.  Do something else... */
}
+5

, . , pthread , , , , . :

  • , , ,
  • sem_t DS. O , "" , , , , . ( , .)
+1

If you want to know if your mutex is locked, I suggest you use it pthread_mutex_trylock. Keep in mind that locking a mutex is a tough operation, you should not lock it to check if it was.

0
source

Source: https://habr.com/ru/post/1769689/


All Articles