信号量、event事件和线程queue
from threading import Thread,Semaphore import time,random sm=Semaphore(5) def task(name): sm.acquire() print('%s 正在上厕所' %name) time.sleep(random.randint(1,3)) sm.release() if __name__ == '__main__': for i in range(20): t=Thread(target=task,args=('路人%s' %i,)) t.start()
from threading import Thread,Event import time event=Event() def light(): print('红灯正亮着') time.sleep(3) event.set() #绿灯亮 def car(name): print('车%s正在等绿灯' %name) event.wait() #等灯绿 print('车%s通行' %name) if __name__ == '__main__': # 红绿灯 t1=Thread(target=light) t1.start() # 车 for i in range(10): t=Thread(target=car,args=(i,)) t.start()
import queue # queue.Queue() #先进先出 # q=queue.Queue(3) # q.put(1) # q.put(2) # q.put(3) # print(q.get()) # print(q.get()) # print(q.get()) # queue.LifoQueue() #后进先出->堆栈 # q=queue.LifoQueue(3) # q.put(1) # q.put(2) # q.put(3) # print(q.get()) # print(q.get()) # print(q.get()) # queue.PriorityQueue() #优先级 q=queue.PriorityQueue(3) #优先级,优先级用数字表示,数字越小优先级越高 q.put((10,'a')) q.put((-1,'b')) q.put((100,'c')) print(q.get()) print(q.get()) print(q.get())