zoukankan      html  css  js  c++  java
  • 信号灯

    import threading,time
    import random
    def light():     ##灯不会应为car而做出任何改变,而是车更加灯做出改变。红灯听
        if not event.isSet():
            event.set() #wait就不阻塞 #绿灯状态
        count = 0
        while True:
            if count < 10:   ##10 以下时绿灯
                print '33[42;1m--green light on---33[0m'
            elif count <13: ## 10 - 12 秒时黄灯
                print '33[43;1m--yellow light on---33[0m'
            elif count <20:   ## 13--19 秒的时候时红灯
                if event.isSet():   ## 判断event.isSet() 如果为真,也就是如果为绿灯,就event.clear(),让它变成红灯
                    event.clear() #clear the green light , switch on the red light
                print '33[41;1m--red light on---33[0m'
            else:
                count = 0
                event.set()   #打开绿灯
            time.sleep(1)
            count +=1


    def car(n):
        while 1:
            time.sleep(random.randrange(3))
            if  event.isSet(): #绿灯
                print "car [%s] is running.." % n
            else:# red light
                print "car [%s] is waiting for the red light.." %n
                event.wait()
                print "Green light is on , car %s is running.............." %n



    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()

    '''
    Events #

    An event is a simple synchronization object;
    the event represents an internal flag, and threads
    can wait for the flag to be set, or set or clear the flag themselves.

    event = threading.Event()

    # a client thread can wait for the flag to be set
    event.wait()     ##等待标志位被设置,如果标志位没有被设置,就阻塞,一直等到标志位被设置才能继续走下去

    # a server thread can set or reset it
    event.set()     ## 设置标志位
    event.clear()   ##清除标志位
    If the flag is set, the wait method doesn’t do anything.
    If the flag is cleared, wait will block until it becomes set again.
    Any number of threads may wait for the same event.
    '''

  • 相关阅读:
    C#实现按键精灵的'找图' '找色' '找字'的功能
    Amazon SES SPF和DKIM设置教程
    你应该知道的最好Webmail邮件客户端,
    8款世界级Webmail工具推荐
    AWS邮件通知服务:实时监控邮件状态
    XenServer:使用XenCenter开设VPS(多图完整版)
    Thinkpad机器BIOS下清除安全芯片和指纹数据的方法
    在ASP.NET Web Application中通过SOAP协议调用Bing搜索服务
    怎么申请 bing api key
    linux挂载硬盘失败,报错!
  • 原文地址:https://www.cnblogs.com/heruxiu/p/13495609.html
Copyright © 2011-2022 走看看