Blocco Qthread Blocks GUI
-
14-11-2019 - |
Domanda
Per un semplice programma di chat Io uso un lib che è avvolto tramite Boost :: Python.
Una semplice GUI è scritta usando Pyqt.La ricezione dei messaggi viene eseguita tramite una chiamata di blocco a detto lib.Per la GUI di aggiornare in modo indipendente la parte di comunicazione è in un qthread.
Mentre assumerei la GUI e la comunicazione per essere indipendenti, la GUI è estremamente insensibile e sembra aggiornare solo quando i messaggi stanno arrivando.
#!/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_()
. Soluzione
This might be caused by the infamous Global Interpreter Lock (GIL). Python does not allow two threads to execute Python code at the same time. In your C function, you have to explicitly release and re-acquire the GIL if you want your GUI code to run in parallel.
This is explained in the Python C API documentation: Thread State and the Global Interpreter Lock.
It boils down to using the following macros in your C extension:
Py_BEGIN_ALLOW_THREADS
// Your expensive computation goes here.
Py_END_ALLOW_THREADS