I'm uisng the psutil library in a thread, that posts my CPU usage statistics periodically. Here's a snippet:

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

I need to stop this thread but I can't seem to understand how. The method cpu_percent is a blocking function that will block for 600 seconds.

I've been digging around and all the examples I saw relied on a tight-loop that checked a flag to see whether the loop should be interrupted but in this case, I'm not sure how to kill the thread.

有帮助吗?

解决方案

Set interval to 0.0 and implement a tighter inner loop in which you can check whether your thread should terminate. It shouldn't be difficult to time it so that the elapsed time between calls to cpu_percent() is roughly the same as 600.

其他提示

You could add astop()method to yourInformationThreadclass that terminates itsrun()loop as shown the following. But note that it won't unblock acpu_percent()call already in progress.

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
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top