Pregunta

Para un programa de chat simple, uso un C LIB que está envuelto a través de Boost :: Python.

Se escribe una GUI simple usando PYQT.Recibir mensajes se realiza a través de una llamada de bloqueo para dijo lib.Para que la GUI se actualice de forma independiente, la parte de comunicación está en un QThread.

Mientras asumo que la GUI y la comunicación son independientes, la GUI es extremadamente no respondida y parece que solo se actualizará cuando entran los mensajes.

#!/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_()

¿Fue útil?

Solución

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
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top