Haiyuan Zhang
Haiyuan Zhang

Reputation: 42822

how to detect mutex condition

I'm wondering if it is possible to implement the following logical under Linux and using POSIX thread library.

given a mutex 
   if (I can get the mutex) {
     lock the mutex
       call fun A
     unlcok the mutex
   }
   else {
      call fun B
   }

I'm new to thread programming under Linux, so just use the pseudo-code to show the logic of the code snippet I'm looking for.

Upvotes: 1

Views: 253

Answers (2)

user623879
user623879

Reputation: 4142

With the typical mutex lock, the thread will sleep until it gets the mutex, and when it does, it will lock all other threads out until it unlocks the mutex. pthread_mutex_trylock is what you need.

if(pthread_mutex_trylock())
{
mutex_unlock()
}
else
{

}

syntax is not correct...not sure what the return value of trylock is so look them up on manpage or google.

Upvotes: 1

Erik
Erik

Reputation: 91270

You're looking for pthread_mutex_trylock

Upvotes: 5

Related Questions