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
分类:
Python
, python-多线程&进程
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于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保姆级教程