Passing an instance of a class to a multiprocess in Python

57 Views Asked by At
   import multiprocessing
   import time

   def sleeper(sec):
   time.sleep(sec)

   if __name__ == "__main__":  
     sec=1
     process = multiprocessing.Process(target=sleeper,args=[sec])
     process.start()

The above code works well. However if the sleeper function is a method in an instance of class that doesn't work. So I need some ideas what should I do if sleeper function is an instant method (like below)


    class SleepingClass:
      def __init__(self, sec):
        self.sec = sec

      def sleeper(sec):
      time.sleep(sec) 

sleepingClass = SleepingClass(1)


if __name__ == "__main__":  
    sec=1
    process = multiprocessing.Process(target=sleepingClass.sleeper,args=[sec])
    process.start()

I tried running method not in instance class and it worked. But when I put it in instance class it did not.

1

There are 1 best solutions below

1
Mark Tolonen On

The class wasn't written correctly. Comments below in code:

import multiprocessing
import time

class SleepingClass:
    def __init__(self, sec):
        self.sec = sec

    def sleeper(self):  # No need for "sec" argument.  Instance has it.
                        # But need "self" for instance method.
        print(f'sleeping for {self.sec} seconds...')
        time.sleep(self.sec) 

if __name__ == "__main__":
    # Create the instance only in main
    sleepingClass = SleepingClass(1)
    # Pass it to the sub-process...no need to pass an argument.
    process = multiprocessing.Process(target=sleepingClass.sleeper)
    process.start()

Output:

sleeping for 1 seconds...