python中的线程:使用target =时检索返回值 [英] Threading in python: retrieve return value when using target=
问题描述
可能重复:
从线程返回值
Possible Duplicate:
Return value from thread
我想获得像这样的一堆服务器的空闲内存":
I want to get the "free memory" of a bunch of servers like this:
def get_mem(servername):
res = os.popen('ssh %s "grep MemFree /proc/meminfo | sed \'s/[^0-9]//g\'"' % servername)
return res.read().strip()
由于可以线程化,所以我想做类似的事情:
since this can be threaded I want to do something like that:
import threading
thread1 = threading.Thread(target=get_mem, args=("server01", ))
thread1.start()
但是现在:如何访问get_mem函数的返回值?
我真的需要采取完整的方法来创建class MemThread(threading.Thread)
并覆盖__init__
和__run__
吗?
But now: how can I access the return value(s) of the get_mem functions?
Do I really need to go the full fledged way creating a class MemThread(threading.Thread)
and overwriting __init__
and __run__
?
推荐答案
您可以创建同步的队列,将其传递给线程函数,并通过将结果推送到队列来使其返回报告,例如:
You could create a synchronised queue, pass it to the thread function and have it report back by pushing the result into the queue, e.g.:
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()
这篇关于python中的线程:使用target =时检索返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!