下面的Python代碼連接到很多服務器,從每個服務器獲取一些信息並返回結果。它目前爲每個連接啓動一個單獨的線程。我想看看如何爲每個連接而不是線程使用單獨的進程來影響性能。這個代碼可以很容易地改變爲使用進程而不是線程?我到底需要做什麼?有什麼風險?如何將此Python代碼更改爲多進程而不是多線程?
的Python 2.6 /平臺的Linux
class ServerInfoGetter(threading.Thread):
def __init__(self, host, port=DEFAULT_PORT, timeout=15):
self.host = host
self.timeout = timeout
self.port = port
self.result = None
threading.Thread.__init__(self)
def get_result(self):
return self.result
def run(self):
try:
serv_check = ServCheck(self.host, \
port=self.port, \
timeout=self.timeout)
serv_check.get_info()
self.result = serv_check
except Exception, err:
logging.debug("Could not run ServCheck for : %s %s",self.host, err)
def process_hosts(hosts_and_ports):
def producer(queue, hosts_and_ports):
for host, ports in hosts_and_ports.items():
for port in ports:
logging.info("processing host: %s:%s", host, port)
thread = ServerInfoGetter(str(host), port)
thread.start()
queue.put(thread, True) # True so block until slot available
results = []
def consumer(queue, total_checks):
while len(results) < total_checks:
thread = queue.get(True)
thread.join()
results.append(thread.get_result())
logging.info("processing hosts")
queue = Queue(QUEUE_SIZE)
prod_thread = threading.Thread(target=producer,
args=(queue,
hosts_and_ports))
cons_thread = threading.Thread(target=consumer,
args=(queue,
calculate_total_checks(hosts_and_ports)))
prod_thread.start()
cons_thread.start()
prod_thread.join()
cons_thread.join()
return results
使用pp – 2011-03-05 21:14:37
@David:Eeek!談論矯枉過正! – 2011-03-05 23:21:32