Home > Software design >  How it possible to break the while loop inside the child proccess
How it possible to break the while loop inside the child proccess

Time:09-10

I've been coding the solution for video recording (cv2 usage) in the background to perform some actions and then stop recording. cv2 lib propose solution to break the recording withing one loop by catching the keyboard interruption:

while True:
    ret,frame= cap.read()
    writer.write(frame)
    cv2.imshow('frame', frame)
   #  waiting for any key pressed
    if cv2.waitKey(1) & 0xFF == 27:
        break

But I want to split this flow into two methods: start() and stop(). As I need to perform some actions between start() and stop() I choose the multiprocessing lib.

import time
from multiprocessing import Process


class Recorder:

    terminator = 0
    proc = None

    def func(self):
        while self.terminator == 0:
            print('func')
            time.sleep(1)
            if self.terminator == 1:
                break

    def start(self):
        self.proc = Process(target=self.func(), args=())
        self.proc.start()

    def stop(self):
        self.terminator = 1
        self.proc.join()


if __name__ == '__main__':
    test = Recorder()
    test.start()
    time.sleep(5)
    test.stop()

But as I understand the variable reassignment does not affect on loop inside the function that called iside the child proccess.

Is it any solution to pass the reassigned variable to child proccess or there is another way to solve the issue?

Making the variable 'global' did not help.

CodePudding user response:

You can use multiprocessing.Event for this.

https://docs.python.org/3/library/multiprocessing.html#multiprocessing.Event

Just replace your terminator int flag with it:

import time
from multiprocessing import Event, Process


class Recorder:
    def __init__(self):
        self.proc = None
        self.terminator = Event()

    def func(self):
        while not self.terminator.is_set():
            print('func')
            time.sleep(1)

    def start(self):
        self.proc = Process(target=self.func, args=())
        self.proc.start()

    def stop(self):
        self.terminator.set()
        self.proc.join()


if __name__ == '__main__':
    test = Recorder()
    test.start()
    time.sleep(5)
    test.stop()
  • Related