Created
August 21, 2018 11:52
-
-
Save matthewrmshin/1ca8fb7a664730f431e7849cd07ec0f4 to your computer and use it in GitHub Desktop.
Quick Python concurrent multiprocessing.Process example
This file contains 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
#!/usr/bin/env python | |
from multiprocessing import Process | |
import sys | |
from time import sleep | |
POLL_DURATION = 0.01 | |
def worker(sleeptime, message): | |
"""Sleep for sleep time and print message.""" | |
sleep(sleeptime) | |
sys.stdout.write('%s\n' % message) | |
def main(): | |
"""Control.""" | |
procs = {} | |
for sleeptime, message in ( | |
(11.0, 'Hello World 11!'), | |
(13.0, 'Hello World 13!'), | |
(10.0, 'Hello World 10!'), | |
(9.0, 'Hello World 9!'), | |
(12.0, 'Hello World 12!'), | |
): | |
proc = Process(target=worker, args=(sleeptime, message)) | |
proc.start() | |
procs[proc.pid] = proc | |
exitcode = 0 | |
while procs: | |
sleep(POLL_DURATION) | |
for pid, proc in procs.copy().items(): | |
if proc.exitcode is not None: | |
proc.join() | |
if proc.exitcode: | |
exitcode = 1 | |
del procs[pid] | |
sys.exit(exitcode) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment