Created
June 4, 2015 20:03
-
-
Save whitews/e6a13268bc1292220e68 to your computer and use it in GitHub Desktop.
Python multiprocessing 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
import random | |
import multiprocessing | |
import time | |
import logging | |
logging.basicConfig( | |
level=logging.DEBUG, | |
format='(%(processName)-10s) %(message)s', | |
) | |
max_processes = 3 | |
class WorkerProcess(multiprocessing.Process): | |
def __init__(self): | |
super(WorkerProcess, self).__init__() | |
self.pause = random.randint(5, 10) | |
self.daemon = True | |
def run(self): | |
logging.debug('sleeping %s', self.pause) | |
time.sleep(self.pause) | |
logging.debug('ending') | |
process_count = 0 | |
while True: | |
if process_count < max_processes: | |
p = WorkerProcess() | |
p.start() | |
process_count = 0 | |
for p in multiprocessing.active_children(): | |
if type(p) is WorkerProcess: | |
process_count += 1 | |
if process_count >= max_processes: | |
time.sleep(1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment