Please explain how we send / receive data from a Queue-driven thread ....
The first subclass of the QThread, defines his method run(), which is run when you call the QThread's .start():
class SimpleThread(QtCore.QThread):
def __init__(self, queue, parent=None):
QtCore.QThread.__init__(self, parent)
self.queue=queue
def run(self):
while True:
arg=self.queue.get()
self.fun(arg)
self.queue.task_done()
def fun(self, arg):
for i in range (3):
print 'fun: %s'%i
self.sleep(1)
return arg+1
Then I declare two instances of Thread (so only two processor cores are taken), sending the instance as an argument self.queue.
self.queue=queue.Queue()
for i in range(2):
thread=SimpleThread(self.queue)
thread.start()
Now, if I understood correctly, thread.start()nothing starts. The real “launch” only happens when I call queue.put():
for arg in [1,2,3]: self.queue.put(arg)
- , "" . Queue put() Queue. .put() : , , "" ( : Queue item.get() `).
fun(). "" fun() return resultValue . self.queue.put(), , , "" ...
EDITED LATER:
(/ ), , . , QThread..., , , :
import os, sys
import threading
import Queue
def callMe(incomingFun, daemon=False):
def execute(_queue, *args, **kwargs):
result=incomingFun(*args, **kwargs)
_queue.put(result)
def wrap(*args, **kwargs):
_queue=Queue.Queue()
_thread=threading.Thread(target=execute, args=(_queue,)+args, kwargs=kwargs)
_thread.daemon=daemon
_thread.start()
_thread.result_queue=_queue
return _thread
return wrap
@callMe
def localFunc(x):
import time
x = x + 5
time.sleep(5)
return x
thread=localFunc(10)
result = thread.result_queue.get()
print result