0

After looking at Python: Executing multiple functions simultaneously, I can successfully make two functions run simultaneously.

Is it possible to make two functions terminate simultaneously?

That is, given the following code:

from multiprocessing import Process

def func1:
     while True:
          # does something and breaks based on key-pressed condition

def func2:
     while True:
          # does something

if __name__=='__main__':
     p1 = Process(target = func1)
     p1.start()
     p2 = Process(target = func2)
     p2.start()

Can I make func2 terminate immediately after func1 finishes (upon the key-pressed condition being satisfied)?

Thanks in advance!

2 Answers2

0

You can wait for p1 to finish with p1.join then terminate p2.

p1 = Process(target = func1)
p2 = Process(target = func2)
p1.start()
p2.start()

p1.join()
p2.terminate()
p2.join()
VarChar42
  • 727
  • 2
  • 13
0

One possible solution is to share a flag between the two processes:

An example:

from multiprocessing import Process, Value
import time


def func1(flag):
    while flag.value:
        print("process1")
        time.sleep(1)


def func2(flag):
    cnt = 0

    while flag.value:
        print("process2")
        cnt += 1
        if cnt == 10:
            flag.value = False

        time.sleep(1)


if __name__ == '__main__':
    run = Value('f', True)

    p1 = Process(target=func1, args=(run,))
    p1.start()
    p2 = Process(target=func2, args=(run,))
    p2.start()
    p1.join()
    p2.join()

Notice that the second process sets the common flag to false after ten iterations, which also makes the process 1 stop.

joaopfg
  • 1,227
  • 2
  • 9
  • 18