【问题标题】:Threading in python: retrieve return value when using target= [duplicate]python中的线程:使用target =时检索返回值[重复]
【发布时间】:2010-04-05 06:43:36
【问题描述】:
可能重复:
Return value from thread
我想像这样获得一堆服务器的“空闲内存”:
def get_mem(servername):
res = os.popen('ssh %s "grep MemFree /proc/meminfo | sed \'s/[^0-9]//g\'"' % servername)
return res.read().strip()
因为这可以线程化,所以我想做这样的事情:
import threading
thread1 = threading.Thread(target=get_mem, args=("server01", ))
thread1.start()
但是现在:如何访问 get_mem 函数的返回值?
我真的需要完全成熟地创建class MemThread(threading.Thread) 并覆盖__init__ 和__run__吗?
【问题讨论】:
标签:
python
memory
multithreading
【解决方案1】:
您可以创建一个同步的queue,将其传递给线程函数,并通过将结果推送到队列中让它报告回来,例如:
def get_mem(servername, q):
res = os.popen('ssh %s "grep MemFree /proc/meminfo | sed \'s/[^0-9]//g\'"' % servername)
q.put(res.read().strip())
# ...
import threading, queue
q = queue.Queue()
threading.Thread(target=get_mem, args=("server01", q)).start()
result = q.get()
【解决方案2】:
为了记录,这是我最终想出的(偏离multiprocessing examples
from multiprocessing import Process, Queue
def execute_parallel(hostnames, command, max_processes=None):
"""
run the command parallely on the specified hosts, returns output of the commands as dict
>>> execute_parallel(['host01', 'host02'], 'hostname')
{'host01': 'host01', 'host02': 'host02'}
"""
NUMBER_OF_PROCESSES = max_processes if max_processes else len(hostnames)
def worker(jobs, results):
for hostname, command in iter(jobs.get, 'STOP'):
results.put((hostname, execute_host_return_output(hostname, command)))
job_queue = Queue()
result_queue = Queue()
for hostname in hostnames:
job_queue.put((hostname, command))
for i in range(NUMBER_OF_PROCESSES):
Process(target=worker, args=(job_queue, result_queue)).start()
result = {}
for i in range(len(hostnames)):
result.update([result_queue.get()])
# tell the processes to stop
for i in range(NUMBER_OF_PROCESSES):
job_queue.put('STOP')
return result