【问题标题】:Will QTimer with mutex cause program to exit unexpectedly?带有互斥锁的 QTimer 会导致程序意外退出吗?
【发布时间】:2020-07-23 02:26:31
【问题描述】:

我们所知道的:

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

我的问题是:

假设我有一个非常耗时的函数 F1 在一个线程中使用带有互斥锁的变量 A。而且,QTimer 正在运行一个循环调用函数 F2,该函数还在另一个线程中使用 A 和互斥锁。如果 F1 正在运行并且 A 被锁定,则 F2 将等待 A 解锁。 F1无限期运行时QTimer会不会堆积很多F2调用?

【问题讨论】:

标签: python multithreading pyqt mutex qtimer


【解决方案1】:

看来 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. test_thread1 没有time.sleep(1)

    test_thread 中的“调用”永远不会被打印,n 正在倒计时。

  2. test_thread1 与 time.sleep(1)

    “呼叫”只出现一次,n 也在倒计时。

【讨论】:

  • 如果 test_thread1 没有启动,n 将按预期递增。
猜你喜欢
  • 2012-10-18
  • 1970-01-01
  • 2011-03-03
  • 1970-01-01
  • 1970-01-01
  • 2014-05-24
  • 2012-12-25
  • 1970-01-01
  • 2011-07-08
相关资源
最近更新 更多