Reputation: 71
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
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:
pthread_barrier_wait
functionpthread_cond_wait
and pthread_cond_signal
functionssem_wait
and sem_post
functionsUpvotes: 1
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