扫码关注官方订阅号
人生最曼妙的风景,竟是内心的淡定与从容!
需要的是线程间通信的方式,当主线程结束时,发一个信号给扫描线程,然后join它。扫描线程收到后,结束自己。线程间通信的方式有很多了,比如用Thread Event。甚至你用redis来通信都没问题
例子
import threading import time class StoppableThread(threading.Thread): def __init__(self, event): super(StoppableThread, self).__init__() self.event = event def run(self): while True: print('OK') if self.event.wait(timeout=1): # 这里的timeout可以是1分钟 break # 表示有人通知要退出了 event = threading.Event() t = StoppableThread(event) t.start() time.sleep(5) event.set() t.join()
用 Condition 替代 sleep
import threading import time cond= threading.Condition() # 条件锁 isStoped=False def thd(cond): print('开始') n=0 while 1: cond.acquire() # 锁 n+=1 print(n) # 要完成的事 cond.wait(1) # 休眠 1秒 , 改为60秒 就是1分钟了 if isStoped:break # 退出线程循环 cond.release() # 解锁 cond.release() # 解锁 print('结束') #启动线程 threading.Thread(target=thd,args=(cond,)).start() time.sleep(10) # 等10秒,让线程干事 cond.acquire() isStoped=True # 设置结束标志 cond.notify() # 唤醒休眠的线程,立即结束。 cond.release()
微信扫码关注PHP中文网服务号
QQ扫码加入技术交流群
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
PHP学习
技术支持
返回顶部
需要的是线程间通信的方式,当主线程结束时,发一个信号给扫描线程,然后join它。扫描线程收到后,结束自己。
线程间通信的方式有很多了,比如用Thread Event。甚至你用redis来通信都没问题
例子
用 Condition 替代 sleep