zoukankan      html  css  js  c++  java
  • 多线程交互

    python线程的事件用于主线程控制其他线程的执行,事件主要提供了三个方法wait、clear、set

    事件处理的机制:全局定义了一个“Flag”,如果“Flag”值为 False,那么当程序执行 event.wait 方法时就会阻塞,如果“Flag”值为True,那么event.wait 方法时便不再阻塞

    clear:将flag设置为False

    set:将flag设置为True

     用 threading.Event 实现线程间通信
    使用threading.Event可以使一个线程等待其他线程的通知,我们把这个Event传递到线程对象中,
    Event默认内置了一个标志,初始值为False。
    一旦该线程通过wait()方法进入等待状态,直到另一个线程调用该Event的set()方法将内置标志设置为True时,
    该Event会通知所有等待状态的线程恢复运行。

    测试代码:

    使用一个线程模拟门禁,当该事件为True的时候,门打开,3秒后自动关闭,如果门是关闭状态需要员工刷卡进入

    #!/usr/bin/env python3
    # -*- coding:utf-8 -*-
    __author__ = 'Alben Xue'
    
    import threading,time,random
    
    def door():
        door_open_times = 0
        while True:
            if door_swiping_event.is_set():
                print("33[32;1m---door opening---33[0m")
                door_open_times += 1
            else:
                print("33[31;1m---door closed---, swipe to open.33[0m")
                door_open_times = 0
                door_swiping_event.wait()
            if door_open_times > 3:
                door_swiping_event.clear()
    
            time.sleep(0.5)
    
    def staff(n):
        print("staff [%s] is coming.." % n)
    
        while True:
            if door_swiping_event.is_set():
                print("33[34;1m---door is opening, passing...33[0m")
                break
            else:
                print('staff [%s] sees door got closed, swipping the card...' % n)
                door_swiping_event.set()
                print('Now the door is open,please pass')
            time.sleep(1)
    
    door_swiping_event = threading.Event()
    
    if __name__ == "__main__":
        door_thread = threading.Thread(target=door)
        door_thread.start()
    
        for i in range(5):
            p = threading.Thread(target=staff,args=(i,))
            time.sleep(random.randrange(3))
            p.start()
  • 相关阅读:
    php.ini 干了些啥?
    为什么你的 phpinfo() 无法显示
    转:反向代理服务器的工作原理
    nginx fastcgi php-fpm的关系梳理
    DOM中offsetLeft与style.left的区别
    移动端与PC端的触屏事件
    移动端适配属性
    移动设备横竖屏监听事件
    关于滚动条滚动不流畅问题
    Oracal
  • 原文地址:https://www.cnblogs.com/alben-cisco/p/7145728.html
Copyright © 2011-2022 走看看