我一直试图让线程正常工作,而且我遇到了问题。默认的线程模块似乎无法返回值,因此我查找了一个解决方案并找到了这个答案 - how to get the return value from a thread in python?
我已经将这个工作用于运行多个线程,但我似乎无法从线程内部打印任何值,直到它们全部完成。这是我目前的代码:
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"
会发生什么,是你获得9x"线程完成",然后"完成",然后是线程打印的所有内容。
但是,删除#wait for values
部分,然后正确打印它们。有什么方法可以让它等待完成,但是从函数内部打印东西?
编辑:这是输出(添加到帖子有点长),它奇怪地反转了打印顺序 - http://pastebin.com/9ZRhg52Q