Python – run 2 loops (same function, different args) concurrently

Question:

I’ve looked at many solutions but none are working for me. I have a simple function (with arg) for a while loop. I would like to run that function with arg1 concurrently with the same function with arg2. At the moment it will only run the first function (output is infinite "func: 1") Here is what I have:

    import multiprocessing
    from multiprocessing import Process

    def func(x):
       while 2 - 1 > 0:
          print("func:", x)     
       
    Process(target=func(1).start())
    Process(target=func(2).start())

I was hoping for an output of randomized "func: 1" "func: 2"
Could someone please explain how to make this "simple" loop function run concurrently with itself?

Edit: Solution that worked for me was:

from multiprocessing import Process

def func(x):
    while True:
        print("func:", x)
if __name__ == '__main__':
 p1 = Process(target=func, args=(1,))
 p2 = Process(target=func, args=(2,))

 p1.start()
 p2.start()
Asked By: Kankan2000

||

Answers:

The syntax you have seems little off. You should pass the function itself to the Process constructor (rather than calling the function with arguments). Please see the correct syntax below:

import multiprocessing
from multiprocessing import Process

def func(x):
    while True:
        print("func:", x)

p1 = Process(target=func, args=(1,))
p2 = Process(target=func, args=(2,))

p1.start()
p2.start()

p1.join()
p2.join()
Answered By: Subhash Prajapati