For a simple chat program i use a c lib that is wrapped via boost::python.
A simple GUI is written using PyQT. Receiving messages is done via a blocking call to said lib. For the GUI to refresh independently the communication part is in a QThread.
While i would assume the GUI and the communication to be independent, the GUI is extremely unresponsive and seems to only update when messages are coming in.
#!/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_()
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