Skip to content

Instantly share code, notes, and snippets.

@whitews
Created June 4, 2015 19:36
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 whitews/182d9557520864e30f66 to your computer and use it in GitHub Desktop.
Save whitews/182d9557520864e30f66 to your computer and use it in GitHub Desktop.
Python threading example
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