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()
  • 相关阅读:
    VS 2008 和 .NET 3.5 Beta 2 发布了
    搭建.NET 3.0环境
    Expression Studio和Silverlight学习资源、安装问题汇总
    Discuz! NT官方社区
    VS2005中ajax安装指南[转]
    IT人 不要一辈子靠技术生存(转)
    Discuz!NT2.5发布 正式版同步开源
    VS2005下开发Silverlight 1.1翻译加补充
    自动化测试案例
    [原]JavaScript必备知识系列开篇
  • 原文地址:https://www.cnblogs.com/alben-cisco/p/7145728.html
Copyright © 2011-2022 走看看