标签:car 同步控制 NPU 子进程 star put eve range 查看
1.多进程
1.方法
进程对象.start() 开启一个进程
进程对象.join() 感知一个进程的结束
进程对象.terminate() 结束一个进程
进程对象.is_alive() 查看某个进程是否存在
2.属性
进程对象.name 进程名
进程对象.pid 进程号
进程对象.daemon 值为True,新的子进程为守护进程
随着主进程代码执行的结束而结束
start之前设置
见代码区
1.子进程中不能有input操作
from multiprocessing import Process def func(): num = input(‘>>> ‘) print(num) if __name__ == ‘__main__‘: Process(target=func).start()
2.进程同步控制——信号量 (多个锁)
from multiprocessing import Process from multiprocessing import Semaphore import time import random def ktv(i,sem): sem.acquire() print(‘%s走进ktv‘%i) time.sleep(random.randint(5,10)) print(‘%s走出ktv‘%i) sem.release() if __name__ == ‘__main__‘: sem = Semaphore(4) for i in range(20): p = Process(target=ktv,args=(i,sem)) p.start()
3.事件——一个信号控制多个进程同时执行或阻塞 红绿灯
from multiprocessing import Process from multiprocessing import Event import time,random def cars(i,e): if not e.is_set(): print(‘车辆%s在等待 ‘%i) e.wait() print(‘车辆%s通过 ‘%i) def traffic_light(e): while 1: if e.is_set(): e.clear() print(‘\033[31m红灯亮了\033[0m‘) else: e.set() print(‘\033[32m绿灯亮了\033[0m‘) time.sleep(2) if __name__ == ‘__main__‘: e = Event() traffic = Process(target=traffic_light,args=(e,)) traffic.start() for i in range(20): car = Process(target=cars, args=(i,e)) car.start() time.sleep(random.randint(1,3))
4.队列
from multiprocessing import Process,Queue def produce(q): q.put(‘from func-produce‘) def consume(q): print(q.get()) if __name__ == ‘__main__‘: q = Queue() p = Process(target=produce,args=(q,)) p.start() c = Process(target=consume,args=(q,)) c.start()
5.消费者,生产者模型——joinablequeue
from multiprocessing import Process,JoinableQueue import time,random def producer(name,food,q): for i in range(5): time.sleep(random.randint(1,2)) f = ‘%s生产了%s%s‘%(name,food,i) print(f) q.put(f) q.join() def consumer(name,q): while 1: c = q.get() if c == None: print(‘%s 得到一个None‘%name) break print(‘\033[31m%s消费了%s\033[0m‘%(name,c)) time.sleep(random.randint(1,2)) q.task_done() if __name__ == ‘__main__‘: q = JoinableQueue() p1 = Process(target=producer,args=(‘alex‘,‘包子‘,q)) p2 = Process(target=producer,args=(‘egon‘,‘馒头‘,q)) p1.start() p2.start() c1 = Process(target=consumer,args=(‘小明‘,q)) c2 = Process(target=consumer,args=(‘小华‘,q)) c1.daemon = True c2.daemon = True c1.start() c2.start() p1.join() p2.join()
标签:car 同步控制 NPU 子进程 star put eve range 查看
原文地址:https://www.cnblogs.com/wan2-0/p/10880001.html