0

I want to create processes without waiting for other processes finish which they can't because they are in an infinite loop.

import time
from multiprocessing import Process


def child_function(param1, param2):
    print(str(param1 * param2))
    while True:
        print("doing some stuff")
        time.sleep(3)


def main_function():
    print("Initializing some things.")
    for _ in range(10):
        Process(target=child_function(3, 5)).start()


if __name__ == '__main__':
    main_function()

This code only starts one process and waits for it to finish. How can I do this?

Edit: Comment answer works fine and the answer below also works fine but for creating thread. Thank you everyone.

fatihsonmez
  • 103
  • 11
  • 1
    The code *doesn't start any subprocesses*. You try to pass `child_function(3, 5)` to the `target` argument of `Process`, so *this calls the function and you go into the function and execute the infinite loop*. You are supposed to provide **the function** – juanpa.arrivillaga Sep 28 '21 at 18:23
  • 2
    So here, just use `Process(target=child_function, args=(3, 5))` – juanpa.arrivillaga Sep 28 '21 at 18:25
  • thank you @juanpa.arrivillaga it works like a charm. – fatihsonmez Sep 28 '21 at 18:39
  • 1
    "This code only starts one process and waits for it to finish." actually nowhere does your code wait for the child process to finish.. for that you need to save a reference to the process object, and call `join()` on it after you `start()` it. Technically it works because python tries to clean-up the existing child processes on exit, but this is kinda like relying on the OS to close your file handles for you when a process exits. It's more reliable to do it yourself. – Aaron Sep 28 '21 at 18:53

1 Answers1

4

Try this Python module Threading

import time
import threading

def child_function(param1, param2):
    print(str(param1 * param2))
    while True:
        print("doing some stuff")
        time.sleep(3)

def main_function():
    print("Initializing some things.")
    for _ in range(10):
        x = threading.Thread(target=child_function, args=(3,5, ))
        x.start()

main_function()

Explanation: as already mentioned in the comments, notice that we are passing the function as opposed to calling it via the thread constructor, Also you can compare Threading vs Multiprocessing and use whichever best suits the project.

Agnij
  • 561
  • 3
  • 13