Python从线程获取函数返回值

Python中利用强大的threading模块可以很容易的实现多线程开发,提高运行速度。这一般是对某个进行大量计算操作的的函数进行多线程处理,然后合并各线程的结果。获取函数返回值的方法可以如下:
1). 利用multiprocessing.pool

import time
import random

def test1(): # run without multi-thread
    t = time.time()
    list = []
    for i in range(10000000):
        list.append(random.choice([0,1,2,3,4,5])) # operation 
    print time.time()-t
    return list

def test2(): # run with multi-thread
    from multiprocessing.pool import Pool
    def func(x):
        return random.choice([0,1,2,3,4,5])
    t = time.time()
    pool = Pool(processes=4) #线程数
    results = pool.map_async(func, range(10000000)) # 用法同map,与之相似的还有apply和apply_async
    print time.time()-t
    return results
r1 = test1()
r2 = test2()

运行结果为7.6s和4.2s。可以看到结果并非线性地减少4倍,这可能与运行结果需要同步有关(没深入研究,猜的)。

2). 利用threading

def func2(m, results, index):
    for i in range(m):
        result[index].append(random.choice([0,1,2,3,4,5]))

from threading import Thread
def test4():
    threads = [None] * 4
    results = [[] for i n range(4)]
    for i in range(4):
        threads[i] = Thread(target=func2, args=(2500000, results, i))
        threads[i].start() # 开始线程
    for i in range(4):
        threads[i].join()  # 等待线程结束后退出
    return results

不过要注意的是只有在处理需要占用大量内存的数据的时候才考虑多线程,因为线程之间的同步问题很重要,因此设计函数的时候就需要注意,否则处理不好反而会产生很多问题。

参考
PS:threading模块multiprocessing模块的文档的说明十分详细,准备好好研究下。

posted on 2016-11-30 00:31  Arkenstone  阅读(10599)  评论(0编辑  收藏  举报