【问题标题】:QMutex.unlock doesn't wake all blocked threadsQMutex.unlock 不会唤醒所有阻塞的线程
【发布时间】:2013-06-03 14:17:28
【问题描述】:

我使用 Qt 4.8.4 和 PyQt 4.10

这是我的测试代码:

#!/usr/bin/env python3

import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *

class Thread1(QThread):
    def run(self):
        print('thread1 %d' % QThread.currentThreadId())
        mutex.lock()
        QThread.sleep(5)
        mutex.unlock()

class Thread2(QThread):
    def run(self):
        tid = QThread.currentThreadId()
        print('%d tid enters' % tid)
        mutex.lock()
        print(tid)

app = QApplication(sys.argv)

print('main thread %d' % QThread.currentThreadId())
mutex = QMutex()
t = Thread1()
t.start()

QThread.sleep(1)
threads = [Thread2() for i in range(10)]
for thread in threads:
    thread.start()

app.exec()

我的问题是:当thread1调用mutex.unlock()时,只有一个被阻塞的线程被唤醒。

这是输出:

main thread 140017224202048
thread1 140016996386560
140016987993856 tid enters
140016979601152 tid enters
140016962815744 tid enters
140016971208448 tid enters
140016672044800 tid enters
140016646866688 tid enters
140016638473984 tid enters
140016954423040 tid enters
140016663652096 tid enters
140016655259392 tid enters
140016987993856

该文档没有说明如何唤醒所有被阻止的内容。我怎样才能做到这一点?谢了

【问题讨论】:

    标签: multithreading qt pyqt pyqt4 python-multithreading


    【解决方案1】:

    mutex 根据定义限制(或保护)一段代码,以便一次只有 一个 线程可以访问它。因此,如果所有线程都等待一个互斥锁,则您不能“​​唤醒”所有线程,也许您需要许多互斥锁(每个“资源”一个)或取决于设计和约束或您的实际项目(因为您从“测试应用程序”)也许semaphore 会更适合。

    【讨论】:

      【解决方案2】:

      尝试QWaitCondition,您可以使用 condition.wakeAll() 来达到您的目的。

      看看wait condition examples

      【讨论】:

        【解决方案3】:

        不知道你是否还需要这个。但我认为你错过了 mutex.unlock 在您的 Thread2 类中。

        您的代码应如下所示:

        class Thread2(QThread):
            def run(self):
                tid = QThread.currentThreadId()
                print('%d tid enters' % tid)
                mutex.lock()
                print(tid)
                mutex.unlock() # line Missing
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-07-08
          • 1970-01-01
          • 2011-01-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-01-05
          • 1970-01-01
          相关资源
          最近更新 更多