Skip to content

Instantly share code, notes, and snippets.

@matthewrmshin
Created August 21, 2018 11:52
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matthewrmshin/1ca8fb7a664730f431e7849cd07ec0f4 to your computer and use it in GitHub Desktop.
Save matthewrmshin/1ca8fb7a664730f431e7849cd07ec0f4 to your computer and use it in GitHub Desktop.
Quick Python concurrent multiprocessing.Process example
#!/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