savkliyildiz
savkliyildiz

Reputation: 1

Multiprocessing with specific functions

I'm stucking in multiprocessing. My code like this. I want to func_once() work on start only. Then other funcitons should work with multiprocessing. But func_once() function works parallel and over and over. How can i handle this?

from multiprocessing import Process
import sys

rocket = 0
def func_once():
    print("this func works one.")

func_once()
def func1():
    global rocket
    print ('start func1')
    while rocket < sys.maxsize:
        rocket += 1
    print ('end func1')

def func2():
    global rocket
    print ('start func2')
    while rocket < sys.maxsize:
        rocket += 1
    print ('end func2')

if __name__=='__main__':
    p1 = Process(target=func1)
    p1.start()
    p2 = Process(target=func2)
    p2.start()

Upvotes: 0

Views: 163

Answers (1)

Booboo
Booboo

Reputation: 44313

You are clearly running under a platform that does not use an operating system fork call to create new processes but rather a spawn call. What this means in simple terms is that when you create a new process, each process starts executing from the very top of the program. That is why:

  1. The code that launches new processes must be within a if __name__ == '__main__': block. If it weren't, you would get into a recursive loop where the processes you just created would be re-executing the code that creates new processes.
  2. The two processes you are creating are each calling func_once (poorly named, as we see).

As @anjandash rightly commented, any code at global scope that you do not want to get executed repeatedly by the processes you create should be moved, namely the call to func_once (you can leave the function definition where it is; it does no real harm there):

if __name__=='__main__':
    func_once() # moved to here
    p1 = Process(target=func1)
    p1.start()
    p2 = Process(target=func2)
    p2.start()
    p1.join()
    p2.join()

Also, each process has its own memory space and sees its own copy of the declaration rocket = 0. That is to say, func1 and func2 will not be incrementing the same instance of rocket.

Upvotes: 1

Related Questions