空のむこうに続く道
状态
文章总数
80篇 总字数
12.6万 运营时长
2年11个月分类
标签
AI Arch BF CLI CSS C语言 Fuwari Giscus GTK HEO Hyprland jQuery JS KDE K签 Linux Lisp LLM Path Pypi Python RSS Textual TUI Vim VTB VUP Whl WP ジサツ 上海 下载 专业 主题 云朵 享乐 代码 优化 伦理 便利店 俄国 光标 内省 内耗 函数式 分析 创伤 创意 判断 前端 北京 参观 友谊 反思 可爱 和风 哲学 商业 回忆 国庆 壁纸 天津 女仆 姐妹 字典 学习 安装 实用 对话 展望 工具 幻想 库 度假 开发环境 开源 归档 微风 心理 志怪 总结 意义 成都 技校 抚远 拥抱 推荐 插件 摄影 政策 故事 故障排查 效果 教程 散文 文件 文化 旅游 日本 日语 时间 显卡 样式 模糊 汉化 治愈 浏览器 浦东 浦西 游戏 滑动 演讲 热力图 特效 猫猫 玩具 环境 甘城 生态 病毒 登录 盘点 直播 破译 社会 社团 视奸 秋游 科幻 移民 窗口 笔记 系统 红枫 线程 终点 终端 经济 编译 美化 美缝 耳机 脑操 自动驾驶 苏州 茅山 萌系 补档 解释器 设计 评论 话术 语言 谷子 走路 轮子 辍学 迁移 运维 重庆 重构 链 随机 静安 音频 项目 颜文字 颜色 首都 魔法 麦金塔 鼠标
423 字
2 分钟
线程的创建、检查与关闭
这几天在做探针软件,其中需要定时请求目标 URL,其中的伪代码是这样的:
import time
target_url = 'https://pinpe.top'
sleep_time = 3600
def monitor():
while True:
ping(target_url)
time.sleep(sleep_time)但这样的话,会因为要等待 time.sleep() 而阻塞软件的流程,导致整个软件都打不开了,我只能用线程来分出一个独立运行的程序出来。
创建线程
首先必须要定义线程,才能创建(启动):
import threading
import time
target_url = 'https://pinpe.top'
sleep_time = 3600
def monitor():
while True:
ping(target_url)
time.sleep(sleep_time)
if __name__ == '__main__':
monitor_thread = threading.Thread(target=monitor)
monitor_thread.start()关键代码解析:
import threading- 导入管理线程的库monitor_thread = threading.Thread(target=monitor)- 定义线程,此线程需要执行monitor()函数monitor_thread.start()- 启动线程
检查线程
使用线程内置的 .is_alive() 方法即可检查线程是否存在:
if monitor_thread.is_alive() == True:
print('线程存在')
else:
print('线程不存在')关闭线程
通常,线程在执行完任务后会自动关闭。但作为一个死循环线程,是无法自己关闭的,而且因为安全原因也无法强制关闭,因此只能用事件来触发关闭:
import threading
import time
target_url = 'https://pinpe.top'
sleep_time = 3600
stop_event = threading.Event()
def monitor():
while not stop_event.is_set():
ping(target_url)
stop_event.wait(sleep_time)
if __name__ == '__main__':
monitor_thread = threading.Thread(target=monitor)
monitor_thread.start()
time.sleep(18000)
stop_event.set()
monitor_thread.join()
stop_event.clear()
monitor_thread = threading.Thread(target=monitor)关键代码解析:
stop_event = threading.Event()- 创建关闭事件while not stop_event.is_set():- 如果触发了这个事件,就不再执行循环stop_event.wait(sleep_time)-time.sleep()的替代方案,可以接受事件触发stop_event.set()- 到时间了,启用这个事件monitor_thread.join()- 等待线程执行完工作stop_event.clear()- 重置事件的状态monitor_thread = threading.Thread(target=monitor)- 如果以后还要使用此线程,可再次定义
如果此时间过长,文中的信息可能会失去时效性,甚至不再准确。

