Python多线程如何实现进度回调 Python多线程任务进度监控方案
时间:2025-12-21 20:39:17 131浏览 收藏
珍惜时间,勤奋学习!今天给大家带来《Python多线程如何实现进度回调 Python多线程任务进度监控方案》,正文内容主要涉及到等等,如果你正在学习文章,或者是对文章有疑问,欢迎大家关注我!后面我会持续更新相关内容的,希望都能帮到正在学习的大家!
使用Queue、共享变量加锁或concurrent.futures结合回调可实现Python多线程进度监控,推荐根据任务结构和更新频率选择线程安全的方案。

在Python中使用多线程执行耗时任务时,常需要实时监控任务进度并回调通知主线程。由于GIL的存在,Python的多线程适合I/O密集型场景,但实现进度回调的核心在于线程间通信机制。
1. 使用 Queue 实现线程安全的进度回调
Queue 是线程安全的,非常适合用于从工作线程向主线程传递进度信息。
示例:模拟文件下载任务的进度更新
import threading
import time
import queue
<p>def download_task(task_id, total_steps, progress_queue):
for step in range(1, total_steps + 1):
time.sleep(0.1) # 模拟 I/O 延迟
progress = int(step / total_steps * 100)
progress_queue.put({
'task_id': task_id,
'progress': progress
})</p><p>def monitor_progress(progress_queue, total_tasks):
completed = 0
while completed < total_tasks:
try:
update = progress_queue.get(timeout=1)
print(f"任务 {update['task_id']} 进度: {update['progress']}%")
if update['progress'] == 100:
completed += 1
except queue.Empty:
continue
print("所有任务完成")</p><h1>启动任务</h1><p>if <strong>name</strong> == "<strong>main</strong>":
q = queue.Queue()
threads = []</p><pre class="brush:python;toolbar:false;">for i in range(3):
t = threading.Thread(target=download_task, args=(i, 10, q))
t.start()
threads.append(t)
monitor_thread = threading.Thread(target=monitor_progress, args=(q, 3))
monitor_thread.start()
for t in threads:
t.join()
monitor_thread.join()2. 使用共享变量 + 回调函数
通过共享数据结构(如字典)记录各任务进度,并配合锁保证线程安全。
import threading
import time
<p>class ProgressTracker:
def <strong>init</strong>(self, task_count, callback):
self.lock = threading.Lock()
self.progress = {i: 0 for i in range(task_count)}
self.callback = callback</p><pre class="brush:python;toolbar:false;">def update(self, task_id, value):
with self.lock:
self.progress[task_id] = value
self.callback(task_id, value)def progress_callback(task_id, progress): print(f"[回调] 任务 {task_id} 当前进度: {progress}%")
def worker(task_id, steps, tracker): for i in range(1, steps + 1): time.sleep(0.1) progress = int(i / steps * 100) tracker.update(task_id, progress)
使用示例
if name == "main": tracker = ProgressTracker(3, progress_callback) threads = []
for i in range(3):
t = threading.Thread(target=worker, args=(i, 10, tracker))
t.start()
threads.append(t)
for t in threads:
t.join()3. 结合 concurrent.futures 的异步回调
使用 ThreadPoolExecutor 可以更方便地管理线程池,并通过 add_done_callback 监控任务完成状态。
虽然不能直接获取中间进度,但可通过共享对象间接实现。
from concurrent.futures import ThreadPoolExecutor
import time
<p>shared_status = {}</p><p>def long_task(task_id, steps):
for i in range(1, steps + 1):
time.sleep(0.1)
shared_status[task_id] = int(i / steps * 100)
return f"任务 {task_id} 完成"</p><p>def done_callback(future):
print(future.result())</p><p>with ThreadPoolExecutor(max_workers=3) as executor:
futures = [executor.submit(long_task, i, 10) for i in range(3)]</p><pre class="brush:python;toolbar:false;">for f in futures:
f.add_done_callback(done_callback)
# 实时监控进度
while any(status < 100 for status in shared_status.values()):
for tid, p in shared_status.items():
print(f"任务 {tid}: {p}%", end=" | ")
print()
time.sleep(0.5)4. 实际应用建议
根据场景选择合适的方案:
- 需要高频率更新进度 → 使用 Queue 避免频繁加锁
- 需结构化管理多个任务 → 使用 共享对象 + 锁
- 任务数量固定且关注完成状态 → concurrent.futures 更简洁
- 避免使用全局变量裸奔,务必保护共享数据
- GUI或Web应用中,回调可触发界面刷新
基本上就这些方法,核心是线程安全的数据传递。选哪种取决于你的任务结构和更新频率需求。
以上就是《Python多线程如何实现进度回调 Python多线程任务进度监控方案》的详细内容,更多关于Python,Python多线程的资料请关注golang学习网公众号!
-
501 收藏
-
501 收藏
-
501 收藏
-
501 收藏
-
501 收藏
-
484 收藏
-
383 收藏
-
295 收藏
-
327 收藏
-
417 收藏
-
438 收藏
-
473 收藏
-
368 收藏
-
438 收藏
-
447 收藏
-
160 收藏
-
285 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 立即学习 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 立即学习 516次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 立即学习 500次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 立即学习 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 立即学习 485次学习