如何停止一个在阻塞函数调用中的线程?
我在一个线程里使用了 psutil
这个库,它定期发布我的CPU使用情况统计数据。下面是一个代码片段:
class InformationThread(threading.Thread):
def __init__(self, *args, **kwargs):
threading.Thread.__init__(self)
def run(self):
while True:
cpu = psutil.cpu_percent(interval=600) #this is a blocking call
print cpu
我需要停止这个线程,但我似乎不太明白该怎么做。这个 cpu_percent
方法是一个阻塞函数,会阻塞600秒。
我查了很多资料,看到的例子都依赖于一个紧密循环,检查一个标志位来判断循环是否应该中断,但在这种情况下,我不太确定怎么结束这个线程。
2 个回答
0
你可以在你的InformationThread
类里添加一个stop()
方法,这个方法可以结束它的run()
循环,像下面这样。但要注意,这个方法不会让已经在运行的cpu_percent()
调用停止。
class InformationThread(threading.Thread):
def __init__(self, *args, **kwargs):
threading.Thread.__init__(self)
self.daemon = True # OK for main to exit even if instance still running
self.running = False
self.status_lock = threading.Lock()
def run(self):
with self.status_lock:
self.running = True
while True:
with self.status_lock:
if not self.running:
break
cpu = psutil.cpu_percent(interval=600) # this is a blocking call
print cpu
def stop(self):
with self.status_lock:
self.running = False
2
把时间间隔设置为0.0,然后在里面写一个更紧凑的循环,这样你就可以检查你的线程是否应该停止。要让调用cpu_percent()
之间的时间差大致保持在600毫秒,其实并不难。