Skip to content

Instantly share code, notes, and snippets.

@playpauseandstop
Created July 20, 2012 12:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save playpauseandstop/3150515 to your computer and use it in GitHub Desktop.
Save playpauseandstop/3150515 to your computer and use it in GitHub Desktop.
Run X processes in background and wait before each of this processes will end.
#!/usr/bin/env python
#
# Run X processes in background and wait before each of this processes will
# end.
#
import sys
import time
from argparse import ArgumentParser
from multiprocessing import Process, Value
DEFAULT_NUMBER = 25
def main():
parser = ArgumentParser()
parser.add_argument('number', default=DEFAULT_NUMBER, nargs='?', type=int,
help='Number of child processes. By default: {}'.\
format(DEFAULT_NUMBER))
args = parser.parse_args(sys.argv[1:])
storage = Value('i', 0)
processes = []
print('Start time: {:d}'.format(int(time.time())))
print
for i in xrange(args.number):
process = Process(target=print_and_sleep,
args=(storage, i + 1))
process.start()
processes.append(process)
for process in processes:
process.join()
print
print('Total result: {:d}'.format(storage.value))
print('End time: {:d}'.format(int(time.time())))
def print_and_sleep(storage, number):
print(' Hello, World! From process #{:d}'.format(number))
time.sleep(number)
print(' Bye, World! From process #{:d}'.format(number))
storage.value += number
if __name__ == '__main__':
try:
main()
except KeyboardInterrupt:
print('\n\nOK! OK! Exiting...')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment