python 线程池案例

线程池

# -*- coding: utf-8 -*-
from multiprocessing import Pool
import os,time,random


def worker(msg):
    t_start = time.time()
    print("第 %s 号 任务开始执行,进程号为%d" % (msg,os.getppid()))
    time.sleep(random.random()*2)
    t_stop = time.time()
    print(msg,"执行完毕,耗时%0.2f" % (t_stop-t_start))


if __name__ == '__main__':

    po = Pool(processes = 3)
    for i in range(0,10):
        # Pool().apply_async(要调用的目标,(传递给目标的参数元祖,))
        # 每次循环将会用空闲的子进程去调用目标
        po.apply_async(worker , args =(i,))

    print("--------- start ---------")
    po.close()  # 关闭进程池,关闭后po不再接收新的请求
    po.join()  # 等待po中所有的子进程执行完成,必须放在close语句之后
    print("--------- end ----------")

多进程

# -*- coding: utf-8 -*-
from multiprocessing import Process
import os,time,random


def worker(msg):
    t_start = time.time()
    print("第 %s 号 任务开始执行,进程号为%d" % (msg,os.getppid()))
    time.sleep(random.random()*2)
    t_stop = time.time()
    print(msg,"执行完毕,耗时%0.2f" % (t_stop-t_start))


if __name__ == '__main__':
    p1 = Process(target=worker,args=(1,))
    p1.start()
    p2 = Process(target=worker,args=(2,))
    p2.start()

你可能感兴趣的:(python 线程池案例)