qLibc
qtokenbucket.c File Reference

Token Bucket implementation. More...

Go to the source code of this file.

Functions

void qtokenbucket_init (qtokenbucket_t *bucket, int init_tokens, int max_tokens, int tokens_per_sec)
 Initialize the token bucket.
 
bool qtokenbucket_consume (qtokenbucket_t *bucket, int tokens)
 Consume tokens from the bucket.
 
long qtokenbucket_waittime (qtokenbucket_t *bucket, int tokens)
 Get the estimate time until given number of token is ready.
 

Detailed Description

Token Bucket implementation.

Current implementation is not thread-safe.

More information about token-bucket: http://en.wikipedia.org/wiki/Token_bucket

qtokenbucket_t bucket;
qtokenbucket_init(&bucket, 500, 1000, 1000);
while (1) {
if (qtokenbucket_consume(&bucket, 1) == false) {
// Bucket is empty. Let's wait
usleep(qtokenbucket_waittime(&bucket, 1) * 1000);
continue;
}
// Got a token. Let's do something here.
do_something();
}
long qtokenbucket_waittime(qtokenbucket_t *bucket, int tokens)
Get the estimate time until given number of token is ready.
void qtokenbucket_init(qtokenbucket_t *bucket, int init_tokens, int max_tokens, int tokens_per_sec)
Initialize the token bucket.
bool qtokenbucket_consume(qtokenbucket_t *bucket, int tokens)
Consume tokens from the bucket.

Definition in file qtokenbucket.c.

Function Documentation

◆ qtokenbucket_init()

void qtokenbucket_init ( qtokenbucket_t *  bucket,
int  init_tokens,
int  max_tokens,
int  tokens_per_sec 
)

Initialize the token bucket.

Parameters
init_tokensthe initial number of tokens.
max_tokensmaximum number of tokens in the bucket.
tokens_per_secnumber of tokens to fill per a second.

Definition at line 76 of file qtokenbucket.c.

◆ qtokenbucket_consume()

bool qtokenbucket_consume ( qtokenbucket_t *  bucket,
int  tokens 
)

Consume tokens from the bucket.

Parameters
buckettockenbucket object.
tokensnumber of tokens to request.
Returns
return true if there are enough tokens, otherwise false.

Definition at line 93 of file qtokenbucket.c.

◆ qtokenbucket_waittime()

long qtokenbucket_waittime ( qtokenbucket_t *  bucket,
int  tokens 
)

Get the estimate time until given number of token is ready.

Parameters
tokensnumber of tokens
Returns
estimated milliseconds

Definition at line 109 of file qtokenbucket.c.