Created
August 2, 2017 03:21
-
-
Save sonya75/9a74211e7335a4a6fe9ab15cd57f0e3b to your computer and use it in GitHub Desktop.
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
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