当前位置: Python基础教程 > 16-多任务-多进程 > 阅读正文

python进程池

2021.7.5.   618 次   840字

python中, 进程和线程一样, 只能运行一次, 运行结束后无法再次调用start, 而是进入销毁阶段, 如果再需要一个进程, 则需要重新创建

对于进程的频繁销毁, 创建, 消耗的时间比较大, 可以使用进程池管理, 首先需要初始化线程池, 然后不再创建线程而是从进程池中取进程, 销毁时并非真正销毁, 而是归还给进程池

进程池实例

在取进程时, 若进程池已被取空, 则进入阻塞状态, 等待其他线程池归还

# coding: utf-8
import multiprocessing
import random
import time


def process(name):
    t_start = time.time()
    print("msg:", name)
    time.sleep(random.random()*2)
    t_stop = time.time()
    print("执行完毕, 耗时%.2f" % (t_stop-t_start))


if __name__ == "__main__":
    pool = multiprocessing.Pool(processes=3)
    for i in range(10):
        index = "hello" + str(i)
        pool.apply_async(process, (index,))  # 方法名, (参数)

    print("start")
    pool.close()
    pool.join()  # 等待子进程结束, 必须在close之后
    print("end")

运行此代码, 结果如下:

start
msg: hello0
msg: hello1
msg: hello2
执行完毕, 耗时0.37
msg: hello3
执行完毕, 耗时0.11
msg: hello4
执行完毕, 耗时0.55
msg: hello5
执行完毕, 耗时1.36
msg: hello6
执行完毕, 耗时0.21
msg: hello7
执行完毕, 耗时1.33
msg: hello8
执行完毕, 耗时1.72
msg: hello9
执行完毕, 耗时1.05
执行完毕, 耗时0.81
执行完毕, 耗时1.73
end

调用线程池时, 后续线程会等待前面线程死亡后, 重新利用

本篇完,还有疑问?

加入QQ交流群:11500065636 IT 技术交流群