Home > Net >  Creating processes that contains infinite loop in python
Creating processes that contains infinite loop in python

Time:09-29

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.

CodePudding user response:

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.

CodePudding user response:

In order to run two or more functions at the same time, you need to use a thread. There are two main threading mudels but I prefer using the one called Threading.

  • Related