典型的Python线程池具有如下结构:
def run(self):
while True:
z=self.some_task_queue.get()
do_work(z)因此,似乎存在对任务队列的持续监控。这种持续监视任务队列的CPU密集度有多高?
引入一些睡眠(几毫秒)时间来降低CPU负载是不是更好?通过这种方式,可以在所有线程都繁忙时停止对任务队列的监控一段时间,从而降低CPU负载。
发布于 2012-03-19 21:26:07
在我的机器上,当.get()上有1000个线程被阻塞时,有0.0%的cpu负载:
#!/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')发布于 2012-03-19 20:42:49
,因此似乎存在对任务队列的持续监控。
这取决于监控对您来说意味着什么。
Queue.get()将在必要时阻塞,直到有项可用,因此这取决于阻塞是如何实现的。
我没有引用,但我认为应该有一个信号处理程序等待唤醒,所以我会说它是“睡眠”的。
https://stackoverflow.com/questions/9770133
复制相似问题