Python - Timer Threads
A Timer starts its work after a delay and can be canceled at any point within that delay time period.
Threading
Python includes sophisticated tools for managing concurrent operations using processes and threads. Even many relatively simple programs can be made to run faster by applying techniques for running parts of the job concurrently using these modules.
subprocess provides an API for creating and communicating with secondary processes. It is especially good for running programs that produce or consume text, since the API supports passing data back and forth through the standard input and output channels of the new process.
The signal module exposes the UNIX signal mechanism for sending events to other processes. The signals are processed asynchronously, usually by interrupting what the program is doing when the signal arrives. Signalling is useful as a coarse messaging system, but other inter-process communication techniques are more reliable and can deliver more complicated messages.
threading includes a high-level, object-oriented API for working with concurrency from Python. Thread objects run concurrently within the same process and share memory. Using threads is an easy way to scale for tasks that are more I/O bound than CPU bound.
The multiprocessing module mirrors threading, except that instead of a Thread class it provides a Process. Each Process is a true system process without shared memory, but multiprocessing provides features for sharing data and passing messages between them. In many cases, converting from threads to processes is as simple as changing a few import statements.
import threading
import time
import logging
logging.basicConfig(level=logging.DEBUG,
format='(%(threadName)-10s) %(message)s',
)
def worker():
while 1:
time.sleep(3)
logging.debug('worker running')
threads = []
for i in range(2):
# t = threading.Thread(target=worker)
t = threading.Timer(1, worker)
threads.append(t)
t.start()
logging.debug('loop running')
将threading.Thread对象改为Timer,构造对象的参数也改为相应的(延迟时间, 函数名).
比较重要的是绿色背景的代码,这个是用于调试。这也提醒了我,线程是进程的一个“逻辑”分支。
调试信息如下:
1 2 3 4 5 6 7 8 9 10 | (MainThread) loop running (MainThread) loop running (Thread-2 ) worker running (Thread-1 ) worker running (Thread-1 ) worker running (Thread-2 ) worker running (Thread-2 ) worker running (Thread-1 ) worker running (Thread-1 ) worker running (Thread-2 ) worker running |
以下是我自己用画图的理解:
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何调试 malloc 的底层源码
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· 25岁的心里话
· 因为Apifox不支持离线,我果断选择了Apipost!
· 零经验选手,Compose 一天开发一款小游戏!
· Trae 开发工具与使用技巧
· 通过 API 将Deepseek响应流式内容输出到前端