如何限制QThread编号

时间:2014-07-27 00:52:13

标签: python pyqt

是否可以通过QtCore.QThread限制Queue启动的线程数。下面的代码启动了与提交的一样多的运行线程。

from PyQt4 import QtCore, QtGui
import Queue as queue

app = QtGui.QApplication([])
theQueue = queue.Queue()

class TheThread(QtCore.QThread):
    def __init__(self, theQueue, parent=None):
        QtCore.QThread.__init__(self, parent)
        self.theQueue = theQueue

    def run(self):
        while True:
            task = self.theQueue.get()
            self.sleep(1) 
            self.theQueue.task_done()

threads=[]
for i in range(1, 3): 
    thread = TheThread(theQueue)
    threads.append(thread)
    thread.start()

for i in range(len(threads)):
    theQueue.put(i)

1 个答案:

答案 0 :(得分:2)

如果您只想使用实际的线程池对象而不是自己创建线程列表,可以使用QThreadPool

from PyQt4 import QtCore, QtGui
import Queue as queue
import time

class Signal(QtCore.QObject):
    sig = QtCore.pyqtSignal(int)

class Worker(QtCore.QRunnable):
    def __init__(self, theQueue, sig):
        QtCore.QRunnable.__init__(self)
        self.theQueue = theQueue
        self.signal = sig

    def run(self):
        while True:
            task = self.theQueue.get()
            if task is None:
                self.theQueue.task_done()
                return
            time.sleep(1)
            print(task)
            self.signal.sig.emit(int(task))
            self.theQueue.task_done()

def result_callback(result):
    print("Got {}".format(result))

MAX_THREADS = 2
def launch_threads():
    theQueue = queue.Queue()
    pool = QtCore.QThreadPool()
    pool.setMaxThreadCount(MAX_THREADS)
    for task in range(MAX_THREADS): 
        sig = Signal()
        sig.sig.connect(result_callback)
        pool.start(Worker(theQueue, sig))

    for i in range(MAX_THREADS * 6): # Sending more values than there are threads
        theQueue.put(i)

    # Tell the threads in the pool to finish
    for i in range(MAX_THREADS):
        theQueue.put(None)

    pool.waitForDone()
    QtCore.QTimer.singleShot(0, QtGui.QApplication.instance().exit)

if __name__ == "__main__":
    app = QtGui.QApplication([])
    QtCore.QTimer.singleShot(0, launch_threads)
    app.exec_()

输出:

0
 1
2
3
4
5
6
 7
8
 9
10
 11
Got 0
Got 1
Got 2
Got 3
Got 4
Got 5
Got 6
Got 7
Got 8
Got 9
Got 10
Got 11