【发布时间】:2019-11-29 14:10:51
【问题描述】:
我已经用 C 语言编写了这段代码,并且有两个 pthread 正在使用这段代码并试图访问互斥锁“firstSection”(在这两个线程中,我们确信传递给函数的互斥锁是相同的)。该代码假设检查两个互斥锁,如果它们都可用,则执行一些发生在函数 safeUnlockTwoMutexes() 中的操作,如果未能获取其中至少一个,则必须等待两秒钟并再次尝试。 (“intersection”互斥锁是安全检查其他互斥锁情况的主锁)
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”作为全局变量)
我想知道如何解决这个问题,线程一个接一个地访问这个部分?
【问题讨论】:
标签: c multithreading pthreads mutex