一、通過event來實現兩個或多個執行緒間的互動,下面是乙個紅綠燈的例子,即起動乙個執行緒做交通指揮訊號燈,乙個執行緒做車輛,車輛行駛按紅燈停,綠燈行的規則。
#!/usr/bin/python
#-*- coding : utf-8 -*-##
##這是我用來練習python執行緒鎖的測試指令碼
import
threading,time
import
random
deflight():
ifnot event.isset(): #
如果沒有設定event
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:
ifevent.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)
def car(n): #
no bug version
while 1:
time.sleep(1) #
讓車慢點
if event.isset(): #
綠燈print("
car [%s] is running..
" %n)
else
:
print("
car [%s] is waiting for the red light..
" %n)
event.wait()
#不斷檢查flag有沒有被設定,如果沒有設定就等著,這個是輸入event等待時間,可以精確到毫秒級
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()
執行結果:
--green light on----green light on--car [0]
isrunning..
--green light on--car [0]
isrunning..
--green light on--car [2] is
running..
--green light on--
--green light on--
--green light on--car [2] is
running..
--green light on--car [2] is
running..
--green light on--
--green light on--car [1] is
running..
car [0]
isrunning..
--yellow light on --car [0]
isrunning..
--yellow light on --car [0]
isrunning..
--yellow light on --
--red light on--
--red light on--
--red light on--car [1] is waiting for
the red light..
--red light on--car [0]
is waiting for
the red light..
--red light on--car [2] is waiting for
the red light..
--red light on--
--red light on--
--green light on--
--green light on--car [2] is
running..
--green light on--car [1] is
running..
--green light on--
--green light on--car [1] is
running..
--green light on--car [0]
isrunning..
--green light on--
--green light on--
...
紅綠燈難題
contest 多校訓練 985專場 problem f 985的紅綠燈難題 time limit 1 sec memory limit 128 mb submit 206 solved 127 submitstatusweb board description 已知紅 綠 黃燈各持續r g y秒,...
Events 事件 紅綠燈
event 用於執行緒之間狀態的同步。對全域性變數不斷地做修改。event threading.event 生成1個event的物件 event.wait 等著設定全域性變數。檢測標誌位是否有設定,如果標誌位沒有設定的話,會一直卡在這裡。等待標誌位被設定。如果標誌位被設定了,代表綠燈,直接通行。wa...
Python併發程式設計 事件,紅綠燈控制
is set 用來檢視乙個事件的狀態 wait 是依據事件的狀態來決定自己是否在wait處阻塞 from multiprocessing import event 乙個訊號可以使得所有的程序都進入阻塞狀態 也可以控制所有的程序解除阻塞 乙個事件被建立之後,預設是阻塞狀態 e event 建立了乙個事...