2014-07-27 2 views
-1

QtCore.QThread으로 시작하는 스레드 수를 Queue을 통해 제한 할 수 있습니까? 아래 코드는 실행 된 스레드가 시작된만큼 시작합니다.QThread 수를 제한하는 방법

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) 
+0

당신이 무슨 뜻인지 확실하지. 'range (1,3)'호출을 통해 많은 스레드를 시작합니다. 'Queue' 객체를 통해 원하는대로 두 개의 스레드에 많은 메시지를 보낼 수 있습니다. 그러면 두 개 이상의 스레드로 끝나지 않을 것입니다. – dano

+0

이제 올바르게 이해한다면 ... [1,2,3,4,5,6,7]에 7 개의 정수가 있다고 가정 해 봅시다. 모든 처리를 수행하는 두 개의 스레드를 만듭니다. 다음으로'for each [1,2,3,4,5,6,7]을 사용하면 : theQueue.put (each)'나는 7 개의 대기열 항목을 시작한다. 큐 아이템 생성을 제외하고'.put()'메소드는 변수 나 값을 저장할 수있게 해줍니다. 나중에이 값 - 데이터는 data ='theQueue.get()'을 사용하여'run()'함수로 검색 할 수 있습니다. 나는'run()'에 데이터를 보내는 유일한 방법은'Thread' 객체를 사용하는 것이라고 생각했습니다. 그러나'theQueue.put()'-'theQueue.get()'은 arg 데이터를 함수에 전달하는 데 사용해야합니다. – alphanumeric

+0

예,'Queue.queue'는 스레드간에 임의의 객체를 안전하게 전달할 수있는 데이터 구조입니다. 따라서'queue.put'을 사용하여 주 스레드가 원하는만큼 많은 항목을 큐에 넣을 수 있습니다. 그런 다음 서로 다른 스레드 나 메인 스레드와 충돌 할 위험없이'queue.get'을 사용하여 큐에서 항목을 끌어낼 수있는만큼 많은 자식 스레드를 가질 수 있습니다. 내 답변에 대한 새로운 편집에서 이것을 증명합니다. – dano

답변

1

방금 ​​대신 자신을 스레드의 목록을 만드는 실제 스레드 풀 개체를 사용하려면 사용할 수 있습니다 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 
+0

'QRunnable'이 신호를 방출하게하는 방법이 있습니까? – alphanumeric

+0

@Sputnix QThreadPool에서 작업자로부터 신호를 보내는 방법을 보여주기 위해 필자의 대답을 업데이트했습니다. – dano

+0

감사합니다. Dano! 대단한 직업! 모든 것이 매우 명확하고 직설적입니다. – alphanumeric

관련 문제