I am new to python object oriented and I am rewriting my existing application as an object oriented version, because now developers are increasing and my code is becoming un-maintainable.
Normally I use multiprocessing queues but I found from this example http://www.doughellmann.com/PyMOTW/multiprocessing/basics.html that I can subclass multiprocessing.Process so I think it’s a good idea and I wrote a class to test like this:
code:
from multiprocessing import Process
class Processor(Process):
def return_name(self):
return "Process %s" % self.name
def run(self):
return self.return_name()
processes = []
if __name__ == "__main__":
for i in range(0,5):
p=Processor()
processes.append(p)
p.start()
for p in processes:
p.join()
However I cannot get back the values, how can I use queues in this way?
EDIT: I want to get the return value and thinking where to put Queues().
Subclassing
multiprocessing.Process:Process needs a
Queue()to receive the results… An example of how to subclassmultiprocessing.Processfollows…On my machine, this results in…
# Using `multiprocessing.Pool`:
FWIW, one disadvantage I’ve found to subclassing
multiprocessing.Processis that you can’t leverage all the built-in goodness ofmultiprocessing.Pool;Poolgives you a very nice API if you don’t need your producer and consumer code to talk to each other through a queue.You can do a lot just with some creative return values… in the following example, I use a
dict()to encapsulate input and output values frompool_job()…This results in:
Obviously there are plenty of other improvements to be made in
pool_job(), such as error handling, but this illustrates the essentials. FYI, this answer provides another example of how to usemultiprocessing.Pool.