带互斥量的QTimer会导致程序意外退出吗?

我们所知道的:

  • 不带单发选项的QTimer将以特定的时间间隔发出超时信号。
  • 超时将在发出时调用一个函数。
  • 互斥锁将锁定变量,以免被另一个线程修改。

我的问题是:

说我有一个非常耗时的函数F1在一个线程中使用带有互斥量的变量A。而且,QTimer正在运行一个循环调用函数F2,该函数还在另一个线程中使用带有互斥量的A。如果F1正在运行且A处于锁定状态,则F2将等待A恢复时钟。当F1无限期运行时,QTimer会堆叠很多F2调用吗?

iCMS 回答:带互斥量的QTimer会导致程序意外退出吗?

Pyqt似乎会处理。这是两个示例线程:

class test_thread(QThread):
    timer = QTimer()

    def __init__(self,parent=None):
        super().__init__(parent=parent)
        self.timer.timeout.connect(self.start)

    def run(self):
        print("call")
        global mutex
        global n
        mutex.lock()
        n = n + 1
        print(n)
        mutex.unlock()

    def process(self):
        self.timer.start(1000)

class test_thread1(QThread):
    def __init__(self,parent=None):
        super().__init__(parent=parent)

    def run(self):
        global mutex
        mutex.lock()
        while True:
            global  n
            n = n - 1
            print(n)
            time.sleep(1)
        mutex.unlock()

测试了两种情况:

  1. 不带time.sleep(1)的test_thread1

    test_thread中的“调用”将永远不会被打印,并且n正在递减计数。

  2. test_thread1与time.sleep(1)

    “通话”只出现一次,而n也正在递减。

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

大家都在问