線程池,鎖,事件
阿新 • • 發佈:2018-05-17
red ase gree edi name get wait lis targe
1。線程池
import threading,time def run(n): s.acquire()#鎖線程 print("thread--%s starting"%n) time.sleep(1) print(‘thread---%s done...‘%n) s.release()#釋放線程 #list=[] s=threading.BoundedSemaphore(5)#信號量。相當於線程池,一次性只能啟動5個線程 for i in range(50): t=threading.Thread(target=run,args=(i,)) t.start() # list.append(t) #for t in list: # t.join() print("完了")
事件:紅綠燈實例
import threading,time event=threading.Event() event.set() def lighter(): count=0 while True: if count>5 and count<10: event.clear()#清除標誌位 print("lighter is reding....") elif count>10: event.set()#設置標誌位 print("lighter is green....") count=0 else: print("lighter is green..") count+=1 time.sleep(1) def car(name): while True: if event.is_set():#判斷標誌位是否設置。 print("[%s] is running"%name) else: print("[%s] is stop"%name) event.wait()#等待標誌位的變化,如果狀態變了,就可以通行了。 print("lighte is green going") time.sleep(1) l=threading.Thread(target=lighter) l.start() c=threading.Thread(target=car,args=(‘aodi‘,)) c.start()
線程池,鎖,事件