Created
June 4, 2015 19:36
-
-
Save whitews/182d9557520864e30f66 to your computer and use it in GitHub Desktop.
Python threading 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 threading | |
import time | |
import logging | |
logging.basicConfig( | |
level=logging.DEBUG, | |
format='(%(threadName)-10s) %(message)s', | |
) | |
max_threads = 3 | |
class WorkerThread(threading.Thread): | |
def __init__(self): | |
super(WorkerThread, 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') | |
thread_count = 0 | |
while True: | |
if thread_count < max_threads: | |
t = WorkerThread() | |
t.start() | |
thread_count = 0 | |
for t in threading.enumerate(): | |
if type(t) is WorkerThread: | |
thread_count += 1 | |
if thread_count >= max_threads: | |
time.sleep(1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment