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

我已经用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”作为全局变量)

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

wqh467212692 回答:两个线程同时访问锁定的互斥锁

您的函数签名按值传递pthread_mutex_tfirstSectionsecondSection。您需要通过指针传递互斥体。

void twoSectionRoute(pthread_mutex_t* firstSection,pthread_mutex_t* secondSection){

然后,在函数内仅使用firstSectionsecondSection而不是&firstSection&secondSection

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

本文链接:https://www.f2er.com/3006907.html

大家都在问