【问题标题】: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__吗?

【问题讨论】:

  • 使用 markdown (daringfireball.net/projects/markdown/syntax) 而不是 HTML 来格式化代码:使用 4 个前导空格缩进代码行。点击帖子编辑器工具栏中的橙色问号了解更多信息。
  • 我意识到这是在提出问题很久之后,但我在threading.Thread 子类中提出了一个相当简单的闭包函数来保存线程的结果。回答这个问题的帖子现在已经结束,所以我也不能在这里回答这个问题,但请参阅stackoverflow.com/a/65447493 以获得快速解释!

标签: 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-23
      • 2021-10-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多