2012-03-19 68 views
3

典型的Python的線程池都會有類似這樣的結構:CPU負荷線程池

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

所以它似乎有任務隊列的連續監測。 CPU密度如何持續監控任務隊列?

爲了降低CPU負載,引入一些 睡眠時間(幾毫秒)會更好嗎? 通過這種方式,可以在所有線程都忙時減少任務隊列的監視並減少CPU負載。

回答

2

0.0% CPU負載,而1000個線程被阻塞在.get()我的機器上:

#!/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') 
+0

良好的工作大加讚賞。 – 2012-03-20 09:58:34

1

因此,看起來有任務隊列的連續監視。

這取決於什麼監測意味着你。

Queue.get()塊,如果需要,直到項目可用,所以它取決於如何實施阻止。

我沒有參考,但我認爲應該有一個信號處理程序等待被喚醒,所以我會說它是「睡覺」。