I'm working on an asynchronous server using asyncio, but I need to monitor a multiprocessing.Event (used to signal termination from another process) inside my async event loop. Here's the simplified version of my server loop:
self.__terminateExchange: Event = multiprocessing.Event()
server = await asyncio.start_server(
self.handle_client,
self.ipAddress,
self.port,
backlog=self.maxSocketConnections
)
async with server:
while not self.__terminateExchange.is_set():
await asyncio.sleep(0.01)
self.__terminateExchange is a multiprocessing.Event. The idea is that another process can call .set() on it, and I want the server to shut down gracefully when that happens.
Problem: This setup is unreliable — sometimes the server exits as expected when the event is set, and sometimes it doesn't. I suspect that checking .is_set() inside the asyncio loop is the issue, possibly due to it being a blocking or non-async-safe call.
What is the correct way to wait for or monitor a multiprocessing.Event in an asyncio event loop?
Is there a non-blocking or async-compatible way to integrate multiprocessing.Event with asyncio?
Would using a thread to bridge the multiprocessing.Event to an asyncio.Event be a better approach?
Any help would be deeply appreciated.
I tried stopping an async code using multiprocessing.Event. Here, when I set the event, it sometimes stops and sometimes doesn't. I also used process.is_alive() to check if the process is still alive and kill it, but it still runs sometimes.
I want to be able to stop the code once the event is set.