-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathtoken_bucket.cpp
39 lines (31 loc) · 954 Bytes
/
token_bucket.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <iostream>
#include <chrono>
#include <thread>
using namespace std;
int main() {
int tokens = 0; // initial number of tokens in the bucket
int rate = 10; // rate at which tokens are added to the bucket
int capacity = 100; // maximum number of tokens the bucket can hold
int request[100];
int n;
cout<<"Enter number of requests: ";
cin>>n;
cout<<"Enter no. of packets per request: ";
for (int i=0;i<n;i++){
cin>>request[i];
}
for (int i=0;i<n;i++) {
// add tokens to the bucket at a fixed rate
tokens = min(tokens + rate, capacity);
// wait for 1 second
this_thread::sleep_for(chrono::seconds(1));
if (tokens >= request[i]) {
// remove the requested tokens from the bucket
tokens -= request[i];
cout << "Request granted, tokens remaining: " << tokens << endl;
} else {
cout << "Request denied, not enough tokens: " << tokens << endl;
}
}
return 0;
}