我想知道是否有可能在Linux下使用POSIX线程库实现以下逻辑。如何检测互斥情况
given a mutex
if (I can get the mutex) {
lock the mutex
call fun A
unlcok the mutex
}
else {
call fun B
}
我是新来的Linux线程编程之下,因此就使用伪码显示的代码片段我要找的逻辑。
我想知道是否有可能在Linux下使用POSIX线程库实现以下逻辑。如何检测互斥情况
given a mutex
if (I can get the mutex) {
lock the mutex
call fun A
unlcok the mutex
}
else {
call fun B
}
我是新来的Linux线程编程之下,因此就使用伪码显示的代码片段我要找的逻辑。
与典型的互斥锁,线程将休眠,直到它得到互斥体,并且当它,它就会出来锁定所有其他线程,直到它解锁互斥量。 pthread_mutex_trylock是你需要的。
if(pthread_mutex_trylock())
{
mutex_unlock()
}
else
{
}
语法不正确......不确定trylock的返回值是什么,所以请在manpage或google上查找它们。
请注意,构造“如果(我可以得到互斥锁)互斥锁”没有任何意义;它本质上具有竞争条件。因此您需要“尝试锁定互斥锁”。 – 2011-03-21 13:37:09