zoukankan      html  css  js  c++  java
  • Python利用Event类模拟红绿灯

    #利用Event类模拟红绿灯
    import threading
    import time
    
    event = threading.Event()
    
    
    def lighter():
        count = 0
        event.set()     #初始值为绿灯
        while True:
            if 5 < count <=10 :
                event.clear()  # 红灯,清除标志位
                print("33[41;1mred light is on...33[0m")
            elif count > 10:
                event.set()  # 绿灯,设置标志位
                count = 0
            else:
                print("33[42;1mgreen light is on...33[0m")
    
            time.sleep(1)
            count += 1
    
    def car(name):
        while True:
            if event.is_set():      #判断是否设置了标志位
                print("[%s] running..."%name)
                time.sleep(1)
            else:
                print("[%s] sees red light,waiting..."%name)
                event.wait()
                print("[%s] green light is on,start going..."%name)
    
    light = threading.Thread(target=lighter,)
    light.start()
    
    car = threading.Thread(target=car,args=("MINI",))
    car.start()
    

      

    #利用Event类模拟红绿灯
    import threading
    import time

    event = threading.Event()


    def lighter():
    count = 0
    event.set() #初始值为绿灯
    while True:
    if 5 < count <=10 :
    event.clear() # 红灯,清除标志位
    print("33[41;1mred light is on...33[0m")
    elif count > 10:
    event.set() # 绿灯,设置标志位
    count = 0
    else:
    print("33[42;1mgreen light is on...33[0m")

    time.sleep(1)
    count += 1

    def car(name):
    while True:
    if event.is_set(): #判断是否设置了标志位
    print("[%s] running..."%name)
    time.sleep(1)
    else:
    print("[%s] sees red light,waiting..."%name)
    event.wait()
    print("[%s] green light is on,start going..."%name)

    light = threading.Thread(target=lighter,)
    light.start()

    car = threading.Thread(target=car,args=("MINI",))
    car.start()
  • 相关阅读:
    【坑】提答题
    Google Code Jam 2014 Round2
    湖北省队互测Week1
    [xyz模拟题]动态维护树的直径
    音乐会的等待【单调栈】
    51nod1202【DP-树状数组维护】
    51nod1113【矩阵快速幂】
    51nod1255【贪心-栈的应用】
    Lightoj1059【最小生成树】
    SPOJ IAPCR2F 【并查集】
  • 原文地址:https://www.cnblogs.com/qtnt/p/12489207.html
Copyright © 2011-2022 走看看