1:第二种开启子进程的方法:
from multiprocessing import Process import os import time class Myprocess(Process): def __init__(self,arg): super().__init__() self.arg = arg print('子进程',os.getppid(),os.getppid(),arg) if __name__ == '__main__': p = Myprocess('666') p.start() p.join() print('主进程',os.getpid(),os.getppid())
守护进程:p.daemon = True
主进程会等待所有的子进程才会结束,主进程负责回收子进程的资源
守护进程会 随着主进程代码执行完毕后而结束,还没有执行完毕的子进程,不会再继续执行
import time from multiprocessing import Process def func(): print('666') time.sleep(3) print('555') if __name__ == '__main__': p = Process(target=func) print('444') p.daemon = True p.start() time.sleep(2) print('主进程')
进程锁:
加锁:
为了保证数据的安全,
在异步的情况下,多个进程又可能同时修改同一份资源
就在修改的过程中加锁
加锁降低了效率,让原来能够同时执行的代码变为顺序执行,异步变同步
保证了数据的安全
import time import json from multiprocessing import Process,Lock def search(): with open('ticket') as f: dic = json.load(f) print('还剩%s张车票'% dic['count']) def get_ticket(person): with open('ticket') as f: dic = json.load(f) time.sleep(0.2) if dic['count'] > 0: print('%s买到票了'%person) dic['count'] -= 1 time.sleep(0.2) with open('ticket','w')as f: json.dump(dic,f) else: print('没有买到票') def ticket(person,lock): search() lock.acquire() get_ticket(person) lock.release() if __name__ == '__main__': lock = Lock() for i in range(6): p = Process(target=ticket,args=(i+1,lock)) p.start()
信号量的实现机制:锁 + 计数器
import time import random from multiprocessing import Process,Semaphore def classroom(person,sem): sem.acquire() print('%s走进了教室'%person) time.sleep(random.random()) print('%s走出了教室'%person) sem.release() if __name__ == '__main__': sem = Semaphore(10) for i in range(100): p = Process(target=classroom,args=(i,sem)) p.start()
事件:Event
阻塞事件:wait() 方法
wait是否阻塞是看event对象内部的一个属性
控制这个属性的值
set() 将这个属性的值改成True
clear() 将这个属性的值改成False
is_set() 判断当前的属性是否为True
import time import random from multiprocessing import Process,Event def traffic(e): print('红灯亮') while True: if e.is_set(): time.sleep(2) print('红灯亮') e.clear() else: time.sleep(2) print('绿灯亮') e.set() def car(e,i): if not e.is_set(): print('%s号车在等绿灯' % i) e.wait() print('%s车通过了绿灯' % i) if __name__ == '__main__': e = Event() p = Process(target=traffic,args=(e,)) p.daemon = True p.start() p_lst = [] for i in range(100): time.sleep(random.randint(1,3)) p = Process(target=car,args=(e,i)) p.start() p_lst.append(p) for p in p_lst: p.join()