#include #include #include #include #include #define MAX_BURST 10 #define INITIAL_LEAKY_RATE 1 int bucketLevel=0; int bucketSize= MAX_BURST; int leakingRate= INITIAL_LEAKY_RATE; /* 1 Carry return per second */ pthread_mutex_t bucketLock = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t bucketChange = PTHREAD_COND_INITIALIZER; void * leak(void * arg) { while (1) { sleep(1); pthread_mutex_lock(&bucketLock); if (bucketLevel>0) bucketLevel-=leakingRate; pthread_mutex_unlock(&bucketLock); pthread_cond_signal(&bucketChange); } } int main(int argc, char * argv[]) { pthread_t tid; char c; int err; err = pthread_create(&tid, NULL, leak, NULL); if (err != 0){ printf("can't create thread \n"); exit(0); } c = getchar(); while (c!=EOF) { pthread_mutex_lock(&bucketLock); while ( bucketLevel >= bucketSize) /* while bucket is full */ pthread_cond_wait(&bucketChange, &bucketLock); bucketLevel+=1; pthread_mutex_unlock(&bucketLock); putchar(c); fflush(stdout); c = getchar(); } exit(0); }