【问题标题】:Blocking QThread blocks GUI阻塞 QThread 阻塞 GUI
【发布时间】:2012-02-20 10:28:17
【问题描述】:

对于一个简单的聊天程序,我使用一个通过 boost::python 包装的 c 库。

使用 PyQT 编写一个简单的 GUI。接收消息是通过阻塞调用来完成的 利伯说。为了让 GUI 独立刷新,通信部分位于 QThread 中。

虽然我假设 GUI 和通信是独立的,但 GUI 极不响应,并且似乎只在消息进入时更新。

#!/usr/bin/env python

import sys

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

import pynetcom2
import time


class NetCom(QThread):

  def __init__(self):
    QThread.__init__(self)
    self.client = pynetcom2.Client()
    self.client.init('127.0.0.1', 4028)
    self.client.provide('myChat', 1)
    self.client.subscribe('myChat', 100)

  def run(self):
    while (1):
      print "Waiting for message..."
      text = self.client.recvStr('myChat', True)
    return



class Netchat(QMainWindow):

    def __init__(self, argv):

        if (len(argv) != 2):
            print "Usage: %s <nickname>" %(argv[0])
            sys.exit(1)
        self.nickname = argv[1]
        print "Logging in with nickname '%s'" %(self.nickname)

        super(Netchat, self).__init__()
        self.setupUI()

        rect = QApplication.desktop().availableGeometry()
        self.resize(int(rect.width() * 0.3), int(rect.height() * 0.6))
        self.show()

        self.com = NetCom()
        self.com.start()

    def setupUI(self):
        centralWidget = QWidget()
        self.setCentralWidget(centralWidget)

        self.testList = QListWidget()

        mainLayout = QHBoxLayout()
        mainLayout.addWidget(self.testList)
        centralWidget.setLayout(mainLayout)

if __name__ == "__main__":
  app = QApplication(sys.argv)
  netchat = Netchat(sys.argv)
  app.exec_()

【问题讨论】:

    标签: python multithreading boost pyqt qthread


    【解决方案1】:

    这可能是由臭名昭著的全局解释器锁 (GIL) 引起的。 Python 不允许两个线程同时执行 Python 代码。在您的 C 函数中,如果您希望 GUI 代码并行运行,则必须显式释放并重新获取 GIL。

    这在 Python C API 文档中有解释:Thread State and the Global Interpreter Lock

    归结为在您的 C 扩展中使用以下宏:

    Py_BEGIN_ALLOW_THREADS
    
    // Your expensive computation goes here.
    
    Py_END_ALLOW_THREADS
    

    【讨论】:

    • 还不够臭名昭著;)现在就像一个魅力!
    猜你喜欢
    • 2013-12-03
    • 1970-01-01
    • 1970-01-01
    • 2020-05-30
    • 2016-07-06
    • 2014-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多