qLibc

Functions
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();
}
qtokenbucket_waittime
long qtokenbucket_waittime(qtokenbucket_t *bucket, int tokens)
Get the estimate time until given number of token is ready.
Definition qtokenbucket.c:109
qtokenbucket_init
void qtokenbucket_init(qtokenbucket_t *bucket, int init_tokens, int max_tokens, int tokens_per_sec)
Initialize the token bucket.
Definition qtokenbucket.c:76
qtokenbucket_consume
bool qtokenbucket_consume(qtokenbucket_t *bucket, int tokens)
Consume tokens from the bucket.
Definition qtokenbucket.c:93

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_tokens | the initial number of tokens.
  max_tokens | maximum number of tokens in the bucket.
  tokens_per_sec | number 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

  bucket | tockenbucket object.
  tokens | number 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

  tokens | number of tokens

Returns
  estimated milliseconds

Definition at line 109 of file qtokenbucket.c.