简体   繁体   中英

Changing local variables of multiprocesses in python

I have a multiprocess set-up that more or less looks as follows:

import multiprocessing

class Worker(multiprocessing.Process):
    def __init__(self, name):
        self.name = name
    def run(self):
        while True:
            #do something
            print( self.name + " is working!")
            #wait a few seconds

def main():
    workers = []
    for a in ["A", "B", "C", "D"]:
        w = Worker(a)
        workers += [w]
        w.start()

What I would like to do is be able to change the name of a worker from main(). Is creating a separate queue for every worker the only way to do this, or is there something nicer? I feel like I continually run into limitations by using multiprocess and I'm not sure what I'm allowed to do anymore.

You could is a Pipe :

import multiprocessing

class Worker(multiprocessing.Process):
    def __init__(self, name):
        self.name = name
        self.change_name_r, self.change_name_w = multiprocessing.Pipe(False)

    def run(self):
        while True:
            #do something
            if self.change_name_r.poll():
                self.name = self.change_name_r.recv()
            print( self.name + " is working!")
            #wait a few seconds

    def change_name(self, new_name):
        self.change_name_w.send(new_name)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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