KRUPASINDHU MOHANTY
KRUPASINDHU MOHANTY

Reputation: 71

pthread_mutex_trylock() use to wait , until other lock has not released

In my code I am using pthread_mutx_trylock() to check thread 1 has completed his job and release the mutexlock or not ?Please let me know either its a valid way or not ?

In Thread 1:

     pthread_mutex_lock(&sync_wait);
     // Waiting for return type.
     pthread_mutex_unlock(&sync_wait);

In Thread 2:

    while (pthread_mutex_trylock(&sync_wait) == 0) {
          }; // Wait until other thread has lock

    // Waiting till thread 1 sync wait lock has not released.
    pthread_mutex_unlock(&sync_wait);

Upvotes: 1

Views: 2459

Answers (2)

Florian Weimer
Florian Weimer

Reputation: 33717

If you want to wake up a specific thread once another thread reaches a certain point in its execution, mutexes are typically not the appropriate synchronization primitive. Alternatives are:

Upvotes: 1

asio_guy
asio_guy

Reputation: 3767

From manual Page

The pthread_mutex_trylock() function shall return zero if a lock on the mutex object referenced by mutex is acquired. Otherwise, an error number is returned to indicate the error.

// so this will loop forever once you aquire lock
    while (pthread_mutex_trylock(&sync_wait) == 0) {
              }; // Wait until other thread has lock

Edit:

This section of code should handle your scenario

while ( int ret = pthread_mutex_trylock( &sync_wait) )
{
  // Unable to get Mutex probably some other thread aquired it
  // sleep for some time usleep or even better use pthread_mutex_timedlock
  // Ideally possible ret values should have been handled but for now
  // this will do
}

and yes pthread_mutex_unlock( );once done with work

here is the manpage also there is a question on so about difference between pthread_mutex_lock and pthread_mutex_trylock here this is another example of handling multiple return values from pthread_try_lock()

Upvotes: 1

Related Questions