• threading Event


    通过threading.Event()可以创建一个事件管理标志,该标志(event)默认为False,event对象主要有四种方法可以调用:

     event.wait(timeout=None):调用该方法的线程会被阻塞,如果设置了timeout参数,超时后,线程会停止阻塞继续执行;
     event.set():将event的标志设置为True,调用wait方法的所有线程将被唤醒;
     event.clear():将event的标志设置为False,调用wait方法的所有线程将被阻塞;

    event.isSet():判断event的标志是否为True。

    实例代码,

    两个线程  countdown,countup, countdown里面触发某个条件时(遍历的值大于5时) 再触发 执行 countup线程。

    from threading import Thread, Event
    import time
    
    # Code to execute in an independent thread
    def countdown(n, started_evt):
        print('countdown starting')
        for i in range(n):
            print("num is %d" % i)
            if i > 5:
                started_evt.set()
            time.sleep(1)
    
    def countup(started_evt):
        print("countup is waiting")
        started_evt.wait()
        print('countup starting')
    
    # Create the event object that will be used to signal startup
    started_evt = Event()
    
    # Launch the thread and pass the startup event
    print('process start')
    t1 = Thread(target=countdown, args=(10,started_evt))
    t2 = Thread(target=countup, args=(started_evt,))
    t1.start()
    t2.start()
    
    print('process is running')

    执行结果:

    [root@localhost comtest]# python3 test2.py
    process start
    countdown starting
    num is 0
    countup is waiting
    process is running
    num is 1
    num is 2
    num is 3
    num is 4
    num is 5
    num is 6
    countup starting
    num is 7
    num is 8
    num is 9

  • 相关阅读:
    「Codeforces 724F」Uniformly Branched Trees
    「笔记」组合入门题选做
    「算法笔记」组合入门与应用
    「算法笔记」可持久化线段树
    「算法笔记」期望 DP 入门
    「NOIP 2016」换教室
    「算法笔记」基础数论
    「笔记」关于乱搞
    python 的列表遍历删除
    Python基础第三篇:函数
  • 原文地址:https://www.cnblogs.com/jkklearn/p/14161824.html
Copyright © 2020-2023  润新知