Threading in python: извлекает возвращаемое значение при использовании target =

Возможный дубликат:
Возвращаемое значение из потока

Я хочу получить "свободную память" из группы серверов вроде этого:

def get_mem(servername):  
    res = os.popen('ssh %s "grep MemFree /proc/meminfo | sed \'s/[^0-9]//g\'"' % servername)  
    return res.read().strip()  

так как это может быть threaded, я хочу сделать что-то вроде этого:

import threading  
thread1 = threading.Thread(target=get_mem, args=("server01", ))  
thread1.start()

Но теперь: как я могу получить доступ к возвращаемым значениям функций get_mem? Мне действительно нужно идти полным путем, создавая class MemThread(threading.Thread) и перезаписывая __init__ и __run__?

Ответ 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

Для записи это то, что я наконец придумал (отклоненный от примеры многопроцессорности

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