如何从python中的线程池获取结果?

如何从python中的线程池获取结果?,第1张

如何从python中的线程获取结果?

Python实际上有一个可以使用的内置线程池,只是没有充分说明:

from multiprocessing.pool import ThreadPooldef foo(word, number):    print (word * number)    r[(word,number)] = number    return numberwords = ['hello', 'world', 'test', 'word', 'another test']numbers = [1,2,3,4,5]pool = ThreadPool(5)results = []for i in range(0, len(words)):    results.append(pool.apply_async(foo, args=(words[i], numbers[i])))pool.close()pool.join()results = [r.get() for r in results]print results

或(使用

map
代替
apply_async
):

from multiprocessing.pool import ThreadPooldef foo(word, number):    print word*number    return numberdef starfoo(args):    """    We need this because map only supports calling functions with one arg.     We need to pass two args, so we use this little wrapper function to    expand a zipped list of all our arguments.    """        return foo(*args)words = ['hello', 'world', 'test', 'word', 'another test']numbers = [1,2,3,4,5]pool = ThreadPool(5)# We need to zip together the two lists because map only supports calling functions# with one argument. In Python 3.3+, you can use starmap instead.results = pool.map(starfoo, zip(words, numbers))print resultspool.close()pool.join()


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5508332.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-13
下一篇 2022-12-13

发表评论

登录后才能评论

评论列表(0条)

保存