【问题标题】:Two threads accessing a locked mutex simultaneously两个线程同时访问锁定的互斥锁
【发布时间】: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


    【解决方案1】:

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

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

    然后,在函数中只使用firstSectionsecondSection 而不是&firstSection&secondSection

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-12-25
      • 2021-02-19
      • 1970-01-01
      • 2014-05-02
      • 1970-01-01
      • 1970-01-01
      • 2013-01-31
      • 1970-01-01
      相关资源
      最近更新 更多