1

I have a function in a class which is activated by another .py file. This function is just there to run simultaneously two other and distinct functions.

It works well on Ubuntu, but not on Windows. Is there any way to have the same result (could be with different code) on both system?

import multiprocessing
import time


class myClass:
    def run_functions(self, var1):
        self.p1 = multiprocessing.Process(target=self.first_function, args=[var1])
        self.p2 = multiprocessing.Process(target=self.second_function)
        self.p1.start()
        self.p2.start()

    def first_function(self, var1):
        print('First function activated ' + var1)
        time.sleep(2)

    def second_function(self):
        print('Second function activated')

x = myClass()
x.run_functions('10')       #Normally activated from another .py file with a list

I don't mind using threading instead. It just needs to work!

martineau
  • 119,623
  • 25
  • 170
  • 301
Heinrich
  • 11
  • 1
  • Let me guess: it does not print? – Klaus D. Apr 06 '21 at 04:44
  • 4
    Tell us what when wrong. The first problem is that the two lines at the bottom should be in an `if __name__ == "__main__":` if clause that keeps the code from re-running when multiprocessing executes a new python and reimports this module. – tdelaney Apr 06 '21 at 04:45

1 Answers1

0

I had the same problem when starting to do multiprocessing on Windows. The issue lies in the way Windows spawns new processes which is different from UNIX. Search for "safe self import".

The easiest way for you is to export first_function and second_function into a separate module and import the module at the beginning of your file. I have described the solution in another topic: https://stackoverflow.com/a/29751273/4141279

RaJa
  • 1,471
  • 13
  • 17