两个线程同时访问一个锁定的互斥体
Two threads accessing a locked mutex simultaneously
我用 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" 作为全局变量)
我想知道如何解决这个问题,并且线程一个接一个地访问这些部分?
您的函数签名按值传递 pthread_mutex_t
值 firstSection
和 secondSection
。您需要通过指针传递互斥量。
void twoSectionRoute(pthread_mutex_t* firstSection, pthread_mutex_t* secondSection){
然后,在函数中只使用 firstSection
和 secondSection
而不是 &firstSection
和 &secondSection
。
如果您按值传递互斥量(如此处),并且它编译,然后复制互斥量本身,因此您最终会出现未定义的行为并且互斥量锁不会在相同状态下运行。
我用 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" 作为全局变量)
我想知道如何解决这个问题,并且线程一个接一个地访问这些部分?
您的函数签名按值传递 pthread_mutex_t
值 firstSection
和 secondSection
。您需要通过指针传递互斥量。
void twoSectionRoute(pthread_mutex_t* firstSection, pthread_mutex_t* secondSection){
然后,在函数中只使用 firstSection
和 secondSection
而不是 &firstSection
和 &secondSection
。
如果您按值传递互斥量(如此处),并且它编译,然后复制互斥量本身,因此您最终会出现未定义的行为并且互斥量锁不会在相同状态下运行。