Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/61.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 两个线程同时访问锁定的互斥锁_C_Multithreading_Pthreads_Mutex - Fatal编程技术网

C 两个线程同时访问锁定的互斥锁

C 两个线程同时访问锁定的互斥锁,c,multithreading,pthreads,mutex,C,Multithreading,Pthreads,Mutex,我用C语言编写了这段代码,有两个pthread正在使用这段代码并试图访问互斥体“firstSection”(在这两个线程中,我们确信传递给函数的互斥体是相同的)。代码假设检查两个互斥体,如果两个互斥体都可用,则执行函数safeUnlockTwoMutexes()中发生的一些操作,如果至少获取其中一个互斥体失败,则必须等待两秒钟,然后重试。(“交叉”互斥锁是安全检查其他互斥锁情况的主锁) void twoSectionRoute(pthread_mutex_t firstSection,pthre

我用C语言编写了这段代码,有两个pthread正在使用这段代码并试图访问互斥体“firstSection”(在这两个线程中,我们确信传递给函数的互斥体是相同的)。代码假设检查两个互斥体,如果两个互斥体都可用,则执行函数safeUnlockTwoMutexes()中发生的一些操作,如果至少获取其中一个互斥体失败,则必须等待两秒钟,然后重试。(“交叉”互斥锁是安全检查其他互斥锁情况的主锁)

void twoSectionRoute(pthread_mutex_t firstSection,pthread_mutex_t secondSection){
bool-pathClear=false;
而(!pathClear){
pthread_mutex_lock(&crossion);
if(pthread\u mutex\u trylock(&firstSection)==0){
if(pthread\u mutex\u trylock(&secondSection)==0){
pathClear=true;
pthread_mutex_unlock(&crossion);
}否则{
pthread_mutex_unlock(&firstSection);
pthread_mutex_unlock(&crossion);
睡眠(2);
}
}否则{
pthread_mutex_unlock(&crossion);
睡眠(2);
}
}
SafeUnlockTwoMutex(第一部分,第二部分,1);
}
现在这段代码的问题是,两个线程几乎可以同时锁定互斥锁“firstSectio”,我不知道为什么。(可能是因为它的类型是递归互斥?!我在文件开头使用了“PTHREAD_mutex_INITIALIZER”作为全局变量)


我想知道如何解决这个问题,线程一个接一个地访问这些部分?

您的函数签名按值传递
pthread\u mutex\t
values
firstSection
secondSection
。您需要通过指针传递互斥体

void twoSectionRoute(pthread_mutex_t* firstSection, pthread_mutex_t* secondSection){
然后,在函数中只使用
firstSection
secondSection
而不是
&firstSection
&secondSection


如果您按值传递互斥体(如此处所示),并且互斥体进行编译,则互斥体本身会被复制,因此最终会出现未定义的行为,互斥锁不会在相同的状态下运行。

您的函数签名按值传递
pthread\u mutex\t
firstSection
secondSection
。您需要通过指针传递互斥体

void twoSectionRoute(pthread_mutex_t* firstSection, pthread_mutex_t* secondSection){
然后,在函数中只使用
firstSection
secondSection
而不是
&firstSection
&secondSection

如果按值传递互斥锁(如此处所示),并且互斥锁进行编译,则互斥锁本身会被复制,因此最终会出现未定义的行为,互斥锁不会在相同的状态下运行