1

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()
Kankan2000
  • 31
  • 4
  • The reason it does not work is because `target=func(1).start()` means "**call `func(1)` now**, and then try to use the `.start` method of the result **now**, and then use that as the `target` for creating the `Process`". You want the `target` to be the function with that `1` argument "bound" to it, following the advice in the linked duplicate, and then call `.start` on **the Process**, not the bound `target` value. Alternately, you can allow the `Process` to do the binding for you. – Karl Knechtel Feb 17 '23 at 00:46
  • See also https://stackoverflow.com/questions/11792629; similar reasoning applies to `multiprocessing` as to `threading`, and the same `args` interface is provided. – Karl Knechtel Feb 17 '23 at 00:55

0 Answers0