Created
July 20, 2012 12:40
-
-
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.
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 | |
# | |
# 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()))) | |
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('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