Python---事件Event

发布时间:2019-09-02 07:56:04编辑:auto阅读(1485)

    Event用法:

    event=threading.Event() #设置一个事件实例

    event.set() #设置标志位

    event.clear() #清空标志位

    event.wait()  #等待设置标志位

    红绿灯实例:

    #红绿灯
    '''标志位设定,代表绿灯,直接通行;标志位被清空,代表红灯;wait()等待变绿灯'''
    
    import threading,time
    
    event=threading.Event()
    
    def lighter():
        '''0<count<5为绿灯,5<count<10为红灯,count>10重置标志位'''
        event.set()     #
        count=0
        while True:
            if count>5 and count<10:
                event.clear()
                print("\033[1;41m red light is on \033[0m")
            elif count>10:
                event.set()
                count=0
            else:
                print("\033[1;42m green light is on \033[0m")
            time.sleep(1)
            count+=1
    
    def car(name):
        '''红灯停,绿灯行'''
        while True:
            if event.is_set():
                print("[%s] is running..."%name)
                time.sleep(0.25)
            else:
                print("[%s] sees red light,need to wait three seconds"%name)
                event.wait()
                print("\033[1;34;40m green light is on,[%s]start going \033[0m"%name)
    
    light=threading.Thread(target=lighter,)
    light.start()
    
    car1=threading.Thread(target=car,args=("Xiaoxiong",))
    car1.start()
    注:车辆检测红绿灯状况的时间与通过改变count计数来改变红绿灯的每次count增加的时间可以随意设定。

关键字