python 进程

1、多进程

1)在主线程中直接构造多个进程

#开进程的方法一:
import time
import random
from multiprocessing import Process
def piao(name):
    print('%s piaoing' %name)
    time.sleep(random.randrange(1,5))
    print('%s piao end' %name)
p1=Process(target=piao,args=('egon',)) #必须加,号
p2=Process(target=piao,args=('alex',))
p3=Process(target=piao,args=('wupeqi',))
p4=Process(target=piao,args=('yuanhao',))
p1.start()
p2.start()
p3.start()
p4.start()
print('主线程')
#开进程的方法二:
import time
import random
from multiprocessing import Process


class Piao(Process):
    def __init__(self,name):
        super().__init__()
        self.name=name
    def run(self):
        print('%s piaoing' %self.name)

        time.sleep(random.randrange(1,5))
        print('%s piao end' %self.name)
p1=Piao('egon')
p2=Piao('alex')
p3=Piao('wupeiqi')
p4=Piao('yuanhao')
p1.start() #start会自动调用run
p2.start()
p3.start()
p4.start()
print('主线程')

 

 

2、进程池

1)要使用mian执行,要不然会报以下错误

RuntimeError: An attempt has been made to start a new process before the   current process has finished its bootstrapping phase
# TODO 进程池的使用
from multiprocessing import Pool
import os, time, random
 
def worker(msg):
    t_start = time.time()
    print("%s开始执行,进程号为%d" % (msg,os.getpid()))
    # random.random()随机生成0~1之间的浮点数
    time.sleep(random.random()*2)
    t_stop = time.time()
    print(msg,"执行完毕,耗时%0.2f" % (t_stop-t_start))
 
def main():
    # 定义一个进程池,最大进程数3
    p = Pool(3) 
    for i in range(0,10):
        # Pool().apply_async(要调用的目标,(传递给目标的参数元祖,))
        # 每次循环将会用空闲出来的子进程去调用目标
        p.apply_async(worker,(i,))
 
    print("----start----")
    p.close()  # 关闭进程池,关闭后po不再接收新的请求
    p.join()  # 等待po中所有子进程执行完成,必须放在close语句之后
    print("-----end-----")
 
if __name__ == '__main__':
    main()

 

posted @ 2022-08-16 20:26  kuaqi  阅读(17)  评论(0编辑  收藏  举报