gpt4 book ai didi

c - pthread_mutex_trylock() 用于等待,直到其他锁尚未释放

转载 作者:行者123 更新时间:2023-11-30 14:53:13 26 4
gpt4 key购买 nike

在我的代码中,我使用 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com