简体   繁体   English

在Python多处理中的池进程之间传递消息

[英]Pass messages between pool processes in Python multiprocessing

I am new to python multiprocessing. 我是python多重处理的新手。 I am writing a redis pubsub module in which a publisher reads data from a database table and publishes the data on a channel. 我正在编写一个redis pubsub模块,其中发布者从数据库表中读取数据并在通道上发布数据。 At subscribers side I intend to create a number of worker processes which can listen to the channel by subscribing to it, get the item from channel and perform some operation on it. 在订户端,我打算创建一些工作进程,这些工作进程可以通过订阅该频道来侦听该频道,从该频道获取项目并对其执行一些操作。 I want to stop all pool processes when any process gets a END string from channel. 当任何进程从通道获取END字符串时,我想停止所有池进程。 For this I am using multiprocessing.Manager().Queue() to communicate among pool processes. 为此,我使用multiprocessing.Manager().Queue()在池进程之间进行通信。 My subscriber module is below: 我的订户模块如下:

import redis
import time
import traceback
import json
import multiprocessing as mp
import contextlib

NO_OF_PROCESS = 4

def newProcess(queue):
    r = redis.StrictRedis()
    p = r.pubsub()
    p.subscribe('subChannel')

    while True:
        print ('Waiting...')
        if (queue.get() == 'END'):
            break 
        # Do some work from message
        message = p.get_message()
        print (message)
        if message:
            data = message['data']
            # If 'END' received than stop all pool processes by setting a message in shared queue
            if data == b'END':
                queue.put('END')
                break
            else:
                data = json.loads(data)
                print (data)
       time.sleep(1)


class Worker:
    def __init__(self, NO_OF_PROCESS):
        self.NO_OF_PROCESS = NO_OF_PROCESS
        self.queue = mp.Manager().Queue()
        self.pool = mp.Pool(processes = NO_OF_PROCESS)

    def doWork(self):
        [self.pool.apply(newProcess, args=(self.queue)) for i in range(self.NO_OF_PROCESS)]



def parallelExec():
    worker = Worker(NO_OF_PROCESS)
    worker.doWork()

parallelExec()

The problem here is I am getting following error when I try to execute: TypeError: newProcess() argument after * must be an iterable, not AutoProxy[Queue] . 这里的问题是我尝试执行时遇到以下错误TypeError: newProcess() argument after * must be an iterable, not AutoProxy[Queue] Please help, also if there is any other approach than I would like to hear. 请帮忙,如果还有其他方法,我想听听。

您不是以可迭代的方式发送args,通过添加逗号将args转换为元组应该可以解决此问题

        [self.pool.apply(newProcess, args=(self.queue,)) for i in range(self.NO_OF_PROCESS)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM