How to implement a multithread token bucket in Python?











up vote
0
down vote

favorite












I'd like to implement a multi-threaded token bucket. The producer will produce tokens for the container whereas the consumer will try to take the tokens from the container. If the number of tokens in the container is equal or greater than the tokens that the consumer asks for, then it will return True and take the tokens; otherwise, the request will be rejected and return False.



I'm trying to use the Semaphore to implement it but found it is a bit weird to access the number of tokens in the container using self.container._Semaphore__value. The reason I want to know the value of the semaphore is I want to make sure the consumer can get enough tokens from the bucket; otherwise, I'll reject it.



Maybe I have some misunderstanding of the whole thing. Can anyone point out a better way to implement a multi-threaded token bucket?



from threading import BoundedSemaphore, Thread, Lock



class TokenBucket(object):



def __init__(self, max_capacity, rate):
self.container = BoundedSemaphore(max_capacity)
self.rate = rate
self.lock = Lock()

def consume(self, n):
self.lock.acquire()
if n <= self.container._Semaphore__value:
for _ in range(n):
self.container.acquire()
return True
else:
return False
self.lock.release()

def produce(self):
self.lock.acquire()
for i in range(self.fill_rate):
try:
self.container.release()
except ValueError:
print("Full, skipping.")
self.lock.release()









share|improve this question






















  • Didn't my answer work for you?
    – Darkonaut
    Nov 14 at 17:31















up vote
0
down vote

favorite












I'd like to implement a multi-threaded token bucket. The producer will produce tokens for the container whereas the consumer will try to take the tokens from the container. If the number of tokens in the container is equal or greater than the tokens that the consumer asks for, then it will return True and take the tokens; otherwise, the request will be rejected and return False.



I'm trying to use the Semaphore to implement it but found it is a bit weird to access the number of tokens in the container using self.container._Semaphore__value. The reason I want to know the value of the semaphore is I want to make sure the consumer can get enough tokens from the bucket; otherwise, I'll reject it.



Maybe I have some misunderstanding of the whole thing. Can anyone point out a better way to implement a multi-threaded token bucket?



from threading import BoundedSemaphore, Thread, Lock



class TokenBucket(object):



def __init__(self, max_capacity, rate):
self.container = BoundedSemaphore(max_capacity)
self.rate = rate
self.lock = Lock()

def consume(self, n):
self.lock.acquire()
if n <= self.container._Semaphore__value:
for _ in range(n):
self.container.acquire()
return True
else:
return False
self.lock.release()

def produce(self):
self.lock.acquire()
for i in range(self.fill_rate):
try:
self.container.release()
except ValueError:
print("Full, skipping.")
self.lock.release()









share|improve this question






















  • Didn't my answer work for you?
    – Darkonaut
    Nov 14 at 17:31













up vote
0
down vote

favorite









up vote
0
down vote

favorite











I'd like to implement a multi-threaded token bucket. The producer will produce tokens for the container whereas the consumer will try to take the tokens from the container. If the number of tokens in the container is equal or greater than the tokens that the consumer asks for, then it will return True and take the tokens; otherwise, the request will be rejected and return False.



I'm trying to use the Semaphore to implement it but found it is a bit weird to access the number of tokens in the container using self.container._Semaphore__value. The reason I want to know the value of the semaphore is I want to make sure the consumer can get enough tokens from the bucket; otherwise, I'll reject it.



Maybe I have some misunderstanding of the whole thing. Can anyone point out a better way to implement a multi-threaded token bucket?



from threading import BoundedSemaphore, Thread, Lock



class TokenBucket(object):



def __init__(self, max_capacity, rate):
self.container = BoundedSemaphore(max_capacity)
self.rate = rate
self.lock = Lock()

def consume(self, n):
self.lock.acquire()
if n <= self.container._Semaphore__value:
for _ in range(n):
self.container.acquire()
return True
else:
return False
self.lock.release()

def produce(self):
self.lock.acquire()
for i in range(self.fill_rate):
try:
self.container.release()
except ValueError:
print("Full, skipping.")
self.lock.release()









share|improve this question













I'd like to implement a multi-threaded token bucket. The producer will produce tokens for the container whereas the consumer will try to take the tokens from the container. If the number of tokens in the container is equal or greater than the tokens that the consumer asks for, then it will return True and take the tokens; otherwise, the request will be rejected and return False.



I'm trying to use the Semaphore to implement it but found it is a bit weird to access the number of tokens in the container using self.container._Semaphore__value. The reason I want to know the value of the semaphore is I want to make sure the consumer can get enough tokens from the bucket; otherwise, I'll reject it.



Maybe I have some misunderstanding of the whole thing. Can anyone point out a better way to implement a multi-threaded token bucket?



from threading import BoundedSemaphore, Thread, Lock



class TokenBucket(object):



def __init__(self, max_capacity, rate):
self.container = BoundedSemaphore(max_capacity)
self.rate = rate
self.lock = Lock()

def consume(self, n):
self.lock.acquire()
if n <= self.container._Semaphore__value:
for _ in range(n):
self.container.acquire()
return True
else:
return False
self.lock.release()

def produce(self):
self.lock.acquire()
for i in range(self.fill_rate):
try:
self.container.release()
except ValueError:
print("Full, skipping.")
self.lock.release()






python multithreading token bucket






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 10 at 1:33









向星雨

1




1












  • Didn't my answer work for you?
    – Darkonaut
    Nov 14 at 17:31


















  • Didn't my answer work for you?
    – Darkonaut
    Nov 14 at 17:31
















Didn't my answer work for you?
– Darkonaut
Nov 14 at 17:31




Didn't my answer work for you?
– Darkonaut
Nov 14 at 17:31

















active

oldest

votes











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














 

draft saved


draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53235273%2fhow-to-implement-a-multithread-token-bucket-in-python%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown






























active

oldest

votes













active

oldest

votes









active

oldest

votes






active

oldest

votes
















 

draft saved


draft discarded



















































 


draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53235273%2fhow-to-implement-a-multithread-token-bucket-in-python%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

How to pass form data using jquery Ajax to insert data in database?

National Museum of Racing and Hall of Fame

Guess what letter conforming each word