Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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()

>Solution :

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()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading