如何在Python中从池线程返回值?

时间:2015-08-25 18:14:54

标签: python multiprocessing pool

我正在尝试在python中学习多处理。 我在Pyhon页面上做了一些例子,但是现在我不知道如何将这两个从池线程中返回值的信息结合起来。

我的一位朋友发给我这段代码http://pastebin.com/g4BLUTcq,但我无法弄清楚如何获得价值。

我的目标是让一个进程不断地从无线电接收器和另一个进程进行录制,以便在下一次录制再次运行时进行信号处理。

也许你可以给我一些提示如何做到这一点。

致以最诚挚的问候,

安德烈亚斯

2 个答案:

答案 0 :(得分:1)

该示例代码构建了自己的线程池类,当python中已有一个时。查看最基本的示例here

从docs.python.org稍加修改:

from multiprocessing import Pool

def f(x):
    return x*x

if __name__ == '__main__':
    with Pool(5) as p:
        my_var = p.map(f, [1, 2, 3])   # This is your return variable now 

如果您确实需要通信并使用队列,请查看本周python模块中的this guide(精彩教程网站)。

编辑:你还提到了多处理和线程,在python中它们是分开的东西,但它们都编码在同一个附近(如果那是你更感兴趣的话,还有一个ThreadPool而不是多处理池)。

答案 1 :(得分:0)

对multiprocessing.Process进行子类化将是这样做的一种方式。我已经编写了一些示例代码,演示了如何启动一个侦听器进程,该进程在使用队列时将收到的记录发送到处理进程。

import multiprocessing
import time
import logging
import random


# recording simlator
def recorder():
    for i in range(5):
        time.sleep(random.randint(1, 10))
        yield 'recording %d' % i
    yield None


# Listener class
class listener(multiprocessing.Process):
    def __init__(self, source, queue):
        super(listener, self).__init__()
        self.source = source
        self.queue = queue

    def run(self):
        for task in self.source():
            if task is None:
                self.queue.put(None)
                break
            logging.info('Recorded %s' % task)
            self.queue.put(task)
        return


# simulating processing function
def processing_func(task):
    time.sleep(random.randint(2, 5))
    return 'Processed %s' % task


# Processor class
class processor(multiprocessing.Process):
    def __init__(self, queue, processing_function):
        super(processor, self).__init__()
        self.queue = queue
        self.processing_function = processing_function

    def run(self):
        while True:
            logging.info('Getting task')
            task = self.queue.get()
            if task is None:
                break
            # print self.queue
            processed_result = self.processing_function(task)
            logging.info(processed_result)
        return


if __name__ == '__main__':
    logging.basicConfig(level=logging.INFO, format='%(asctime)s  %(levelname)-8s %(message)s',
                        datefmt='%m-%d %H:%M:%S')

    # make a queue sending tasks from listener to processor
    new_queue = multiprocessing.Queue()
    # make a listener
    rec = listener(recorder, new_queue)
    # make a processor
    pro = processor(new_queue, processing_func)

    # start processing and listening
    pro.start()
    rec.start()

    # Finish recording and processing
    rec.join()
    pro.join()
相关问题