Skip to content

Instantly share code, notes, and snippets.

@caetanus
Created November 1, 2015 00:10
Show Gist options
  • Save caetanus/33d09f59f8a5bcafed31 to your computer and use it in GitHub Desktop.
Save caetanus/33d09f59f8a5bcafed31 to your computer and use it in GitHub Desktop.
# -*- coding: utf-8 -*-
import threading
from collections import deque
import functools
import traceback
MAX_THREADS = 8
class ThreadPool(object):
_lock = threading.Lock()
_threads = set()
_waiting_threads = deque()
@classmethod
def run(cls, target, *args, **kwargs):
def start_thread():
with cls._lock:
if len(cls._threads) < MAX_THREADS and len(cls._waiting_threads):
thread = cls._waiting_threads.popleft()
cls._threads.add(thread)
thread.start()
@functools.wraps(target)
def runner(*args, **kwargs):
try:
target(*args, **kwargs)
except:
traceback.print_exc()
with lock:
cls._threads.remove(threading.current_thread())
start_thread()
new_thread = threading.Thread(target=runner, name=target.__name__,
args=args, kwargs=kwargs)
with cls._lock:
cls._waiting_threads.append(new_thread)
start_thread()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment