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

复制代码

 

posted on   思此狂  阅读(594)  评论(0编辑  收藏  举报

编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· Vue3状态管理终极指南:Pinia保姆级教程

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示