Henry
Henry

Reputation: 113

Run concurrent processes in same class with multiprocessing library

I need to run multiple class functions in parallel with the 'multiprocessing' library but I have not been able to find a guide or an answer for my specific issue. My problem is that only the first process is starting (or running I do not know the exact difference here).

To illustrate the issue, I have set up the following example:

import multiprocessing
import time

class parallel_printer(multiprocessing.Process):

    def __init__(self, freq_0, freq_1, freq_2):
        self.freq_0 = freq_0
        self.freq_1 = freq_1
        self.freq_2 = freq_2

    def print_0(self):
        while True:    
            now = time.localtime()
            if now.tm_sec % self.freq_0 == 0:
                print('printer 0')
                time.sleep(1.0)

    def print_1(self):
        while True:    
            now = time.localtime()
            if now.tm_sec % self.freq_1 == 0:
                print('printer 1')
                time.sleep(1.0)

    def print_2(self):
        while True:    
            now = time.localtime()
            if now.tm_sec % self.freq_2 == 0:
                print('printer 2')
                time.sleep(1.0)

    def start_printer(self):

        p_0 = multiprocessing.Process(target = self.print_0())
        p_1 = multiprocessing.Process(target = self.print_1())
        p_2 = multiprocessing.Process(target = self.print_2())

        p_0.start()
        p_1.start()
        p_2.start()


class Tester(object):

    def __init__(self):        

        self.freq_0 = 3
        self.freq_1 = 7
        self.freq_2 = 11

        self.parallel_printer = parallel_printer(self.freq_0, self.freq_1, self.freq_2)

    def start_Tester(self):
        self.parallel_printer.start_printer()


if __name__ == '__main__':
tester = Tester()
tester.start_Tester()      

Upvotes: 2

Views: 364

Answers (1)

finefoot
finefoot

Reputation: 11234

As you can read in the Python docs for multiprocessing.Process, you need to pass the "calling object" for the target argument.

Your code should look like:

p_0 = multiprocessing.Process(target=self.print_0)
p_1 = multiprocessing.Process(target=self.print_1)
p_2 = multiprocessing.Process(target=self.print_2)

If you write self.print_0() instead of self.print_0, you're not passing the calling object as you should do, but you call the function and pass the return value.

Upvotes: 5

Related Questions