Skip to content

Instantly share code, notes, and snippets.

@sonya75
Created August 2, 2017 03:21
Show Gist options
  • Save sonya75/9a74211e7335a4a6fe9ab15cd57f0e3b to your computer and use it in GitHub Desktop.
Save sonya75/9a74211e7335a4a6fe9ab15cd57f0e3b to your computer and use it in GitHub Desktop.
from threading import Lock, Condition
class ThreadLimiter:
def __init__(self, maxvalue):
self.maxvalue = maxvalue
self.currentvalue = 0
self.mainlock = Lock()
self.maincond = Condition(self.mainlock)
def setmax(self, maxval):
self.mainlock.acquire()
self.maxvalue = maxval
self.maincond.notifyAll()
self.mainlock.release()
def acquire(self):
self.mainlock.acquire()
while True:
if self.maxvalue > self.currentvalue:
self.currentvalue += 1
self.mainlock.release()
return
self.maincond.wait()
def release(self):
self.mainlock.acquire()
self.currentvalue -= 1
self.maincond.notify(1)
self.mainlock.release()
def __enter__(self):
self.acquire()
def __exit__(self, exc_type, exc_val, exc_tb):
self.release()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment