Join a thread and get the return value of a function

Lie Ryan lie.1296 at gmail.com
Thu Dec 24 13:19:46 EST 2009


On 12/25/2009 2:02 AM, mattia wrote:
> Il Fri, 25 Dec 2009 00:35:55 +1100, Lie Ryan ha scritto:
>
>> On 12/25/2009 12:23 AM, mattia wrote:
>>> Hi all, is there a way in python to get back the value of the function
>>> passed to a thread once the thread is finished? Something like
>>> pthread_join() in C?
>>>
>>> Thanks, Mattia
>>
>> use a Queue to pass the value out?
>
> Yes, it can be a solution, but are you indirectly telling me that there
> is no way then?

looking at the threading.py source code, it is clear that the return 
value of Thread.run() is ignored, but this is a workaround:

import threading

class MyThread(threading.Thread):
     def join(self):
         super(MyThread, self).join()
         return self.result

class Worker(MyThread):
     def run(self):
         total = 0
         for i in range(random.randrange(10000, 100000)):
             total += i
         self.result = total

import random
ts = [Worker() for i in range(100)]
for t in ts:
     t.start()

for t in ts:
     print t.join()



More information about the Python-list mailing list