Join a thread and get the return value of a function

Aahz aahz at pythoncraft.com
Wed Jan 13 15:03:12 EST 2010


In article <4b33b0ce$1 at dnews.tpgi.com.au>,
Lie Ryan  <lie.1296 at gmail.com> wrote:
>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()

That seems like extra work when you can just do this without subclassing
threading.Thread:

for t in ts:
     t.join()
     print t.result
-- 
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

"If you think it's expensive to hire a professional to do the job, wait
until you hire an amateur."  --Red Adair



More information about the Python-list mailing list