Python线程池的CPU负载

4

典型的Python线程池结构如下:

def run(self):
    while True:
        z=self.some_task_queue.get() 
        do_work(z)

看起来任务队列正在进行持续监控。

这种持续监控任务队列会占用多少CPU资源?

是否应该引入一些sleep(几毫秒)时间来降低CPU负载?通过这种方式,当所有线程都繁忙时,可以停止对任务队列的监控,并降低CPU负载。

2个回答

3

我的机器上有1000个线程在.get()上阻塞,但CPU负载只有0.0%

#!/usr/bin/env python
from __future__ import print_function
import os
import time
from threading import Thread
from Queue import Queue

try: import psutil # pip install psutil
except ImportError:
    psutil = None

def f(queue):
    while True:
        item = queue.get() # block until an item is available
        print("got %s" % (item,))
        break # end thread

# create threads
q = Queue()
threads = [Thread(target=f, args=(q,)) for _ in xrange(1000)]

# starts them
for t in threads:
    t.daemon = True # die with the program
    t.start()


# show cpu load while the threads are blocked on `queue.get()`
if psutil is None:
    print('Observe cpu load yourself (or install psutil and rerun the script)')
    time.sleep(10) # observe cpu load
else:
    p = psutil.Process(os.getpid())
    for _ in xrange(10):
        print("cpu %s%%" % (p.get_cpu_percent(interval=0),))
        time.sleep(1)


# finish threads
for i in range(len(threads)):
    q.put_nowait(i) #note: queue is unlimited so there is no reason to wait

for t in threads: t.join() # wait for completion
print('done')

1
看起来任务队列正在持续监控。
这取决于你对“监控”的理解。
如果需要,Queue.get() 将阻塞直到有可用的项目,因此它取决于阻塞的实现方式。
我没有参考资料,但我认为应该有一个信号处理程序在等待被唤醒,所以我会说它正在“睡眠”。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接