写在前面:html
在使用这些共享API的时候,咱们要注意如下几点:安全
在UNIX平台上,当某个进程终结以后,该进程须要被其父进程调用wait,不然进程成为僵尸进程(Zombie)。因此,有必要对每一个Process对象调用join()方法 (实际上等同于wait)。对于多线程来讲,因为只有一个进程,因此不存在此必要性。多线程
multiprocessing提供了threading包中没有的IPC(好比Pipe和Queue),效率上更高。应优先考虑Pipe和Queue,避免使用Lock/Event/Semaphore/Condition等同步方式 (由于它们占据的不是用户进程的资源)。app
多进程应该避免共享资源。在多线程中,咱们能够比较容易地共享资源,好比使用全局变量或者传递参数。在多进程状况下,因为每一个进程有本身独立的内存空间,以上方法并不合适。此时咱们能够经过共享内存和Manager的方法来共享资源。但这样作提升了程序的复杂度,并由于同步的须要而下降了程序的效率。dom
Process.PID中保存有PID,若是进程尚未start(),则PID为None。函数
window系统下,须要注意的是要想启动一个子进程,必须加上那句if __name__ == "main",进程相关的要写在这句下面。spa
条件同步和条件变量同步差很少意思,只是少了锁功能,由于条件同步设计于不访问共享资源的条件环境。操作系统
围绕一个标志位来进行判断线程
event=threading.Event():条件环境对象,初始值 为False;设计
event.isSet():返回event的状态值;
event.wait():若是 event.isSet()==False将阻塞线程;
event.set(): 设置event的状态值为True,全部阻塞池的线程激活进入就绪状态, 等待操做系统调度;
event.clear():恢复event的状态值为False。
案例一:
import threading,time class Boss(threading.Thread): def run(self): print("BOSS:今晚你们都要加班到22:00。") event.isSet() or event.set() time.sleep(5) print("BOSS:<22:00>能够下班了。") event.isSet() or event.set() class Worker(threading.Thread): def run(self): event.wait() print("Worker:哎……命苦啊!") time.sleep(0.25) event.clear() event.wait() print("Worker:OhYeah!") if __name__=="__main__": event=threading.Event() threads=[] for i in range(5): threads.append(Worker()) threads.append(Boss()) for t in threads: t.start() for t in threads: t.join()
案例二:
import threading,time import random def light(): if not event.isSet(): event.set() #wait就不阻塞 #绿灯状态 count = 0 while True: if count < 10: print('\033[42;1m--green light on---\033[0m') elif count <13: print('\033[43;1m--yellow light on---\033[0m') elif count <20: if event.isSet(): event.clear() print('\033[41;1m--red light on---\033[0m') else: count = 0 event.set() #打开绿灯 time.sleep(1) count +=1 def car(n): while 1: time.sleep(random.randrange(10)) if event.isSet(): #绿灯 print("car [%s] is running.." % n) else: print("car [%s] is waiting for the red light.." %n) if __name__ == '__main__': event = threading.Event() Light = threading.Thread(target=light) Light.start() for i in range(3): t = threading.Thread(target=car,args=(i,)) t.start()
队列由于是可使2遍都开口,因此FIFO,栈是开头封闭,只能从底部出,因此先进后出
Python Queue模块有三种队列及构造函数:
一、Python Queue模块的FIFO队列先进先出。 class queue.Queue(maxsize)
二、LIFO相似于堆,即先进后出。 class queue.LifoQueue(maxsize)
三、还有一种是优先级队列级别越低越先出来。 class queue.PriorityQueue(maxsize)
注意:列表时线程不安全的,队列是安全的,内部有一把锁保证了我数据的安全
import queue # 队列长度可为无限或者有限,默认是Queue(0),表示无限长 d = queue.Queue(2) #可经过Queue的构造函数的可选参数maxsize来设定队列长度,若是maxsize小于1就表示队列长度无限。 d.put('hello', 0) # 第一个item为必需的,为插入项目的值; # 第二个block为可选参数,默认为1。若是队列当前为空且block为1,线程阻塞,直到空出一个数据单元 # 若是block为0,put方法将引起Full异常。 d.put('world', 0) # d.put('2017', 0) # 第三个,阻塞报异常 print(d.get()) # get()方法从队头删除并返回一个项目。可选参数为block,默认为True。 # 若是队列为空且block为True,get()就使调用线程暂停,直至有项目可用。 # 若是队列为空且block为False,队列将引起Empty异常。 print(d.get())
队列的方法
此包中的经常使用方法(q = Queue.Queue()): q.qsize() 返回队列的大小 q.empty() 若是队列为空,返回True,反之False q.full() 若是队列满了,返回True,反之False q.full 与 maxsize 大小对应 q.get([block[, timeout]]) 获取队列,timeout等待时间 q.get_nowait() 至关q.get(False)非阻塞 q.put(item) 写入队列,timeout等待时间 q.put_nowait(item) 至关q.put(item, False) q.task_done() 在完成一项工做以后, q.task_done() 函数向任务已经完成的队列发送一个信号
实例一:
import threading,queue from time import sleep from random import randint class Production(threading.Thread): def run(self): while True: r=randint(0,100) q.put(r) print("生产出来%s号包子"%r) sleep(1) class Proces(threading.Thread): def run(self): while True: re=q.get() print("吃掉%s号包子"%re) if __name__=="__main__": q=queue.Queue(10) threads=[Production(),Production(),Production(),Proces()] for t in threads: t.start()