我已经用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”作为全局变量)
我想知道如何解决此问题,线程又一个接一个地访问此部分?
答案 0 :(得分:2)
您的函数签名按值传递pthread_mutex_t
值firstSection
和secondSection
。您需要通过指针传递互斥体。
void twoSectionRoute(pthread_mutex_t* firstSection, pthread_mutex_t* secondSection){
然后,在函数内仅使用firstSection
和secondSection
而不是&firstSection
和&secondSection
。
如果按值传递互斥锁(如此处所示)并进行编译,则该互斥锁本身将被复制,因此最终会出现未定义的行为,并且互斥锁不会在同一状态下运行。