0

I've just been trying to get threading working properly and I've hit a problem. The default thread module doesn't seem to be able to return values, so I looked up a solution and found this answer - how to get the return value from a thread in python?

I've got this working for getting multiple threads running, but I can't seem to print any values from inside the thread until they've all finished. Here is the code I currently have:

import random
from multiprocessing.pool import ThreadPool

#only 2 threads for now to make sure they don't all finish at once
pool = ThreadPool(processes=2)

#should take a few seconds to process
def printNumber(number):
    num = random.randint( 50000, 500000 )
    for i in range( num ):
        if i % 10000 == 0:
            print "Thread " + str( number ) + " progress: " + str( i )
        test = random.uniform( 0, 10 ) ** random.uniform( 0, 1 )
    return number

thread_list = []

#Execute threads
for i in range(1,10):
   m = pool.apply_async(printNumber, (i,))
   thread_list.append(m)

#Wait for values and get output
totalNum = 0
for i in range( len( thread_list ) ):
   totalNum += thread_list[i].get()
   print "Thread finished"

# Demonstrates that the main process waited for threads to complete
print "Done"

What happens, is you get 9x "Thread finished", then "Done", then everything that was printed by the threads.

However, remove the #wait for values part, and it prints them correctly. Is there any way I can keep it waiting for completion, but print things from inside the function?

Edit: Here is the output (a bit long to add to the post), it weirdly reverses the print order - http://pastebin.com/9ZRhg52Q

Community
  • 1
  • 1
Peter
  • 3,186
  • 3
  • 26
  • 59
  • What platform are you using? I can't reproduce that behavior you're describing. It prints exactly the way you'd expect for me on Linux. – dano Oct 08 '14 at 00:47
  • I'm on windows using it inside Maya, wouldn't have thought it'd be that much different – Peter Oct 08 '14 at 00:53
  • 1
    I just tested on Windows, and it works fine there, too. My guess is that the issue has something to do with the way stdout is handled within Maya. – dano Oct 08 '14 at 00:57
  • Damn, that's not cool. Can't really integrate it into my code if I can't find a way of getting it working haha. Also it prints the values with the latest first (starting at thread 9 going to 0) which doesn't seem to make sense – Peter Oct 08 '14 at 01:02

0 Answers0