多种方法实现 python 线程池

运行环境:python 3.6.0

 

1、过去:

使用threadpool模块,这是个python的第三方模块,具体使用方式如下:

# -*- encoding: utf-8 -*-

import threadpool
import time


def sayhello (a):
    print("hello: " + a)
    time.sleep(2)


def main():
    global result
    seed = ["a", "b", "c"]
    """ 多线程 """
    start = time.time()
    task_pool = threadpool.ThreadPool(5)

    requests = threadpool.makeRequests(sayhello, seed)
    for req in requests:
        task_pool.putRequest(req)
    task_pool.wait()
    end = time.time()
    time_m = end - start
    print("time: " + str(time_m))

    """ 单线程 """
    start1 = time.time()
    for each in seed:
        sayhello(each)
    end1 = time.time()
    print("time1: " + str(end1 - start1))


if __name__ == '__main__':
    run()
    main()


# 运行结果
"""
hello: a
hello: b
hello: c
over
hello: a
hello: b
hello: c
time: 2.022491216659546
hello: a
hello: b
hello: c
time1: 6.006936311721802
"""

threadpool是一个比较老的模块了,现在虽然还有一些人在用,但已经不再是主流了,关于python多线程,现在已经开始步入未来(future模块)了。

2、未来:

使用concurrent.futures模块,这个模块是python3中自带的模块,但是,python2.7以上版本也可以安装使用,具体使用方式如下:

# -*- encoding: utf-8 -*-

from concurrent.futures import ThreadPoolExecutor
import time


def sayhello(a):
    print("hello: " + a)
    time.sleep(2)


def main():
    seed = ["a", "b", "c"]

    """ 单线程 """
    start1 = time.time()
    for each in seed:
        sayhello(each)
    end1 = time.time()
    print("time1: " + str(end1-start1))
    
    """ 多线程<submit> """
    start2 = time.time()
    with ThreadPoolExecutor(3) as executor:
        for each in seed:
            executor.submit(sayhello, each)
    end2 = time.time()
    print("time2: " + str(end2 - start2))
    
    """ 多线程<map> """
    start3 = time.time()
    with ThreadPoolExecutor(3) as executor1:
        executor1.map(sayhello, seed)
    end3 = time.time()
    print("time3: " + str(end3 - start3))


if __name__ == '__main__':
    main()


# 输出结果
"""
hello: a
hello: b
hello: c
time1: 6.018568754196167
hello: a
hello: b
hello: c
time2: 2.006592035293579
hello: a
hello: b
hello: c
time3: 2.0062594413757324
"""

注意到一点:

concurrent.futures.ThreadPoolExecutor,在提交任务的时候,有两种方式,一种是submit()函数,另一种是map()函数,两者的主要区别在于:

1. map可以保证输出的顺序, submit输出的顺序是乱的

2. 如果你要提交的任务的函数是一样的,就可以简化成map。但是假如提交的任务函数是不一样的,或者执行的过程之可能出现异常(使用map执行过程中发现问题会直接抛出错误)就要用到submit()

3. submit和map的参数是不同的,submit每次都需要提交一个目标函数和对应的参数,map只需要提交一次目标函数,目标函数的参数放在一个迭代器(列表,字典)里就可以。

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值