Return value from thread
I suggest you instantiate a Queue.Queue before starting the thread, and pass it as one of the thread's args: before the thread finishes, it .put
s the result on the queue it received as an argument. The parent can .get
or .get_nowait
it at will.
Queues are generally the best way to arrange thread synchronization and communication in Python: they're intrinsically thread-safe, message-passing vehicles -- the best way to organize multitasking in general!-)
You should pass a Queue instance as a parameter then you should .put() your return object into the queue. You can gather the return value via queue.get() whatever object you put.
Sample:
queue = Queue.Queue()thread_ = threading.Thread( target=target_method, name="Thread1", args=[params, queue], )thread_.start()thread_.join()queue.get()def target_method(self, params, queue): """ Some operations right here """ your_return = "Whatever your object is" queue.put(your_return)
Use for multiple threads:
#Start all threads in thread pool for thread in pool: thread.start() response = queue.get() thread_results.append(response)#Kill all threads for thread in pool: thread.join()
I use this implementation and it works great for me. I wish you do so.
Use lambda to wrap your target thread function and pass its return value back to the parent thread using a queue. (Your original target function remains unchanged without extra queue parameter.)
Sample code:
import threadingimport queuedef dosomething(param): return param * 2que = queue.Queue()thr = threading.Thread(target = lambda q, arg : q.put(dosomething(arg)), args = (que, 2))thr.start()thr.join()while not que.empty(): print(que.get())
Output:
4