我已经用C语言编写了这段代码,并且有两个使用此代码并试图访问互斥锁“ firstSection”的pthread(在我们两个人中,我们都确保传递给函数的互斥锁是相同的)。该代码假定检查两个互斥锁,并且如果两个互斥锁均可用,则执行一些在函数safeUnlockTwoMutexes()中发生的操作,如果无法获取其中至少一个,则必须等待两秒钟,然后重试。 (“相交”互斥锁是用于安全检查其他互斥锁状况的主锁)
void twoSectionRoute(pthread_mutex_t firstSection,pthread_mutex_t secondSection){
bool pathClear = false;
while (!pathClear){
pthread_mutex_lock(&intersection);
if (pthread_mutex_trylock(&firstSection) == 0){
if (pthread_mutex_trylock(&secondSection) == 0){
pathClear = true;
pthread_mutex_unlock(&intersection);
} else {
pthread_mutex_unlock(&firstSection);
pthread_mutex_unlock(&intersection);
sleep(2);
}
} else {
pthread_mutex_unlock(&intersection);
sleep(2);
}
}
safeUnlockTwoMutexes(firstSection,secondSection,1);
}
现在,这段代码的问题是两个线程几乎都可以同时锁定互斥锁“ firstSectio”,我不知道为什么。 (也许因为它的类型是递归互斥体?!我在文件开头使用“ pthREAD_MUTEX_INITIALIZER”作为全局变量)
我想知道如何解决此问题,线程又一个接一个地访问此部分?