Python使用线程生成线程并在主要完成时终止

时间:2012-11-14 03:19:42

标签: python multithreading

我有一个脚本可以执行很多操作,我想生成一个监视cpu和内存使用情况的线程。

监测部分是:

import psutil
import time
import datetime

def MonitorProcess():
    procname = "firefox"

    while True:
            output_sys = open("/tmp/sysstats_counter.log", 'a')

            for proc in psutil.process_iter():
                    if proc.name == procname:
                            p = proc

            p.cmdline

            proc_rss, proc_vms =  p.get_memory_info()
            proc_cpu =  p.get_cpu_percent(1)

            scol1 = str(proc_rss / 1024)
            scol2 = str(proc_cpu)

            now = str(datetime.datetime.now())

            output_sys.write(scol1)
            output_sys.write(", ")
            output_sys.write(scol2)
            output_sys.write(", ")
            output_sys.write(now)
            output_sys.write("\n")

            output_sys.close( )

            time.sleep(1)

我确信有更好的方法来进行监控,但我不关心这一点。

主脚本调用:

RunTasks() # which runs the forground tasks 
MonitorProcess() # Which is intended to monitor the tasks CPU and Memory Usage over time

我想同时运行这两个功能。为此,我假设我必须使用线程库。那么接近的方法就是:

thread = threading.Thread(target=MonitorProcess())
thread.start

或者我离开了?

当RunTasks()函数完成时,如何让MonitorProcess()自动停止?我假设我可以测试该进程是否存在,如果它不是杀死函数???

1 个答案:

答案 0 :(得分:2)

听起来你想要一个守护程序线程。来自docs

  

线程可以标记为“守护程序线程”。这个标志的意义在于,当只剩下守护进程线程时,整个Python程序都会退出。初始值继承自创建线程。可以通过守护程序属性设置标志。

在您的代码中:

thread = threading.Thread(target=MonitorProcess)
thread.daemon = True
thread.start()

即使守护程序线程仍处于活动状态,程序也会在主要退出时退出。设置并启动监控线程后,您将需要运行前台任务。