0

Why is the section that should only run once running every time? Does this make sense and what is the proper way to run a target function as a separate thread ?

The code is taken from a very simple example at https://pymotw.com/2/multiprocessing/basics.html

import multiprocessing

print("Starting Main - This should only run ONCE")


def worker1(num):
    """thread worker function"""
    print("Worker:", num)
    return


if __name__ == '__main__':
    jobs = []
    for i in range(5):
        p = multiprocessing.Process(target=worker1, args=(i,))
        jobs.append(p)
        print("Starting Process=", i)
        p.start()

OUTPUT Console:

[Running] python "e:\Projects\Python-Test\test1.py"
Starting Main - This should only run ONCE
Starting Process= 0
Starting Process= 1
Starting Process= 2
Starting Process= 3
Starting Process= 4
Starting Main - This should only run ONCE # (??????? WHY )
Worker: 1
Starting Main - This should only run ONCE (???????)
Worker: 0
Starting Main - This should only run ONCE
Worker: 4
Starting Main - This should only run ONCE
Worker: 2
Starting Main - This should only run ONCE
Worker: 3

[Done] exited with code=0 in 0.45 seconds
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Hakan Usakli
  • 492
  • 5
  • 11
  • 4
    Because each worker has to import the function from that file, and your `print` is outside the `if __name__ == '__main__':` block? It's literally in the docs you've linked to: [*"Due to the way the new processes are started, the child process needs to be able to import the script containing the target function."*](https://pymotw.com/2/multiprocessing/basics.html#importable-target-functions) – jonrsharpe Jul 20 '18 at 09:13
  • Understood. I was not expecting this behaviour at all and I am not sure if it makes sense either. A function name is given as the process execution target but the python interpreter runs code not part of that function, just because it is in the same file. I find that weird when everything in Python is about easy and good readability. – Hakan Usakli Jul 20 '18 at 14:18
  • The module is executed when you import it. That's how Python works, and the whole reason you have `if __name__ == '__main__':` in there to begin with - to distinguish between when it's being imported and directly executed. If you're not executing the module content, you're not executing the class, variable and function definitions and there's nothing to import anyway. Also it's not clear how you think that impacts readability - if anything, surely it's easier to follow than something that special-cases mechanics for import vs. execution. – jonrsharpe Jul 20 '18 at 14:22
  • See e.g. https://stackoverflow.com/q/419163/3001761 – jonrsharpe Jul 20 '18 at 14:23

0 Answers0