Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
starts n processes with some random amount of work, and they exit whenever the first one is finished
import os
import random
import time
from multiprocessing import Pool, Event
def init_pool_processes(the_shutdown_event):
Initialize each process with the global shutdown event
global shutdown_event
shutdown_event = the_shutdown_event
def wait(ignored):
sleep_time = random.randint(1, 16)
sleep_time_left = sleep_time
print(f"😴 Sleeping for {sleep_time} seconds...")
while True:
if shutdown_event.is_set():
print("💀 Shutdown event set, exiting...")
if sleep_time_left <= 0:
print(f"😃 Done sleeping for {sleep_time} seconds!")
sleep_time_left -= 1
# starts a pool of n processes with some random amount of work, and they all stop as soon
# as the first one is finished
if __name__ == '__main__':
print(f"👷‍♂️ Starting {os.cpu_count()} worker processes")
shutdown_event = Event()
with Pool(processes=os.cpu_count(), initializer=init_pool_processes, initargs=(shutdown_event,)) as pool:, range(os.cpu_count()))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment