Skip to content

Instantly share code, notes, and snippets.

@kamuridesu
Last active October 13, 2022 12:28
Show Gist options
  • Select an option

  • Save kamuridesu/556f25e26a62d50dfcb04a4e77a68498 to your computer and use it in GitHub Desktop.

Select an option

Save kamuridesu/556f25e26a62d50dfcb04a4e77a68498 to your computer and use it in GitHub Desktop.
from time import sleep
import multiprocessing as mp
def sc(arg):
try:
print(f"called {arg}")
sleep(arg)
print(f"exited {arg}")
except KeyboardInterrupt:
pass
def handle(p):
print(p)
def main():
process_pool: list[mp.Process] = []
args = [*range(10)][::-1]
LIMIT = 3
for arg in args:
process = mp.Process(target=sc, args=(arg,))
process_pool.append(process)
process.start()
if len(process_pool) >= LIMIT:
old_pp: list[mp.Process] = process_pool.copy()
new_pp = []
while True:
for process in old_pp:
if process.is_alive():
new_pp.append(process)
elif process.exitcode != 0:
handle(process)
if len(new_pp) != len(old_pp):
process_pool = new_pp
break
new_pp = []
[x.join() for x in process_pool]
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment