Reputation: 1578
I have a system formed by 3 processes: a main one, and 2 child processes.
The first child process is constantly checking for a condition, and once this condition is verified, something happens in the second child process. This can happen multiple times.
So I was wondering...is it possible to use a mp.Event as trigger? I'm thinking of...switching it, like a True/False bool variable, and looking for it in the second process. Something like this:
main process
import multiprocessing as mp
from multiprocessing import set_start_method, Queue, Event
from p01 import P01_Initializer
from p02 import P02_Initializer
import time
import sys
def main():
set_start_method("spawn")
sw_event = mp.Event()
p01 = mp.Process(target=P01_Initializer, args=(sw_event, ))
p01.daemon = True
p01.start()
p02 = mp.Process(target=P01_Initializer, args=(sw_event, ))
p02.daemon = True
p02.start()
## close everything after 15 seconds
t_start = time.time()
while True:
if time.time() - t_start > 15:
p01.terminate()
p02.terminate()
sys.exit(0)
if __name__ == "__main__":
main()
first child process
import time
def P01_Initializer(sw_event):
process_01 = P01(sw_event)
process_01.run()
class P01():
def __init__(self, sw_event):
self.sw_event = sw_event
def run(self):
while True:
if condition:
self.sw_event.set() ### switching it, like a bool variable
second child process
import time
def P02_Initializer(sw_event):
process_02 = P02(sw_event)
process_02.run()
class P02():
def __init__(self, sw_event):
self.sw_event = sw_event
def run(self):
while True:
if self.sw_event == False:
do nothing
else:
self.sw_event.set() ### switch it back to False, waiting for next occurence
do something
Is something like this possible, or should I just use a boolean variable and pass it between processes using a Queue?
Upvotes: 0
Views: 293
Reputation: 1578
Ok, so basically you can set/unset (?) the event by using:
sw_event.set()
sw_event.clear()
once you do that, you can check the status of the event by:
sw_event.is_set()
Upvotes: 3