Python 實現紅綠燈

2022-06-23 18:33:09 字數 2901 閱讀 4162

一、通過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--

...