随笔分类 -  Python使用

注意事项,python多线程,要注意主线程生命周期
摘要:1 要注意,如果单开一个脚本,使用多线程脚本的多线程函数,是运行不到的,因为主线程会因为单独运行脚本运行结束而结束生命周期,结束过早,根本执行不了多线程。 阅读全文
posted @ 2025-12-29 11:12 偷懒的阿贤 阅读(27) 评论(0) 推荐(0)
守护线程 + 优雅关闭
摘要:import threadingimport time class TaskManager: def __init__(self): self.should_stop = False self.thread = None def background_task(self): """后台任务,但支持优 阅读全文
posted @ 2025-12-26 15:20 偷懒的阿贤 阅读(4) 评论(0) 推荐(0)
daemon=True
摘要:daemon=True表示这是"守护线程":当主程序结束时,无论守护线程是否完成任务,都会立即强制终止。 import threadingimport time def worker(): time.sleep(5) print("✅ 线程任务完成") # 普通线程,不使用 daemon=True( 阅读全文
posted @ 2025-12-26 15:20 偷懒的阿贤 阅读(13) 评论(0) 推荐(0)
带回调的非阻塞任务
摘要:import threadingimport time def async_with_callback(task_func, callback=None): """非阻塞任务带回调""" def wrapper(): result = task_func() if callback: callbac 阅读全文
posted @ 2025-12-26 15:17 偷懒的阿贤 阅读(37) 评论(0) 推荐(0)
函数封装(可复用)
摘要:import threadingimport time def run_async(task_func, *args, **kwargs): """一行启动非阻塞任务""" threading.Thread(target=task_func, args=args, kwargs=kwargs, da 阅读全文
posted @ 2025-12-26 15:16 偷懒的阿贤 阅读(16) 评论(0) 推荐(0)
使用threading
摘要:import threadingimport time # 定义后台任务def background_task(): time.sleep(3) # 模拟耗时操作 print("✅ 后台任务完成") # 启动非阻塞任务(核心3行)thread = threading.Thread(target=ba 阅读全文
posted @ 2025-12-26 15:15 偷懒的阿贤 阅读(29) 评论(0) 推荐(0)