Python_事件event

  1. 事件(event)
    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 flags 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 clear, wait will block until it becomes set again.
    Any number of threads may wait for the same event.
    通过event来实现线程之间的交互

    redlight = False

    while True:
    if counter > 30:
    redlight = True
    if counter >50:
    redlight = False
    counter = 0

下面以一个红绿灯的程序作为例子来理解一下事件:

# Author : Xuefeng

import threading, time

# 实例化事件
event = threading.Event()


def light():
    '''
    定义灯的函数,红灯亮5秒绿灯亮5秒。
    :return: 
    '''
    count = 0
    # 事件置位
    event.set()
    while True:
        if count > 5 and count < 10:          # Change for red light
            event.clear()       # clear the flag
            print("\033[41;1m red light is on...\033[0m")
        elif count > 10:
            event.set()         # set the flag
            count = 0
        else:
            print("\033[42;1m green light is on...\033[0m")
        time.sleep(1)
        count += 1

def car(name):
    '''
    定义汽车模型,红灯停,绿灯行
    :param name: 汽车的名字
    :return: 
    '''
    while True:
        if event.is_set():          # Green light
            print("[%s] running..." % name)
            time.sleep(1)
        else:
            print("[%s] sees red light, waitting..." %name)
            event.wait()
            print("\033[42;1m Green light on, [%s] startting...\033[0m" %name)

# 创建灯的线程
Light = threading.Thread(target=light)
Light.start()
# 创建3个小汽车
Car_1 = threading.Thread(target=car, args=("Tom",))
Car_2 = threading.Thread(target=car, args=("Jim",))
Car_3 = threading.Thread(target=car, args=("Mary",))
Car_1.start()
Car_2.start()
Car_3.start()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值