Last active
October 13, 2022 12:28
-
-
Save kamuridesu/556f25e26a62d50dfcb04a4e77a68498 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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