python查看函数返回类型_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模块的文档的说明十分详细,准备好好研究下。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值