在我的代码中,我使用 pthread_mutx_trylock() 来检查线程 1 是否已完成他的任务 工作并释放互斥锁吗?请让我知道它是否有效?
在线程 1 中:
pthread_mutex_lock(&sync_wait);
// Waiting for return type.
pthread_mutex_unlock(&sync_wait);
在线程 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);
最佳答案
来自手册页面
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
编辑:
这部分代码应该可以处理您的场景
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
}
是的pthread_mutex_unlock( );
一旦完成工作
这是manpage 还有一个关于 pthread_mutex_lock 和 pthread_mutex_trylock 之间差异的问题 here 这是另一个 example of handling multiple return values from pthread_try_lock()
关于c - pthread_mutex_trylock() 用于等待,直到其他锁尚未释放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47321256/