#include #include #include #include #include #include #define MAX_BURST 10 #define FILL_RATE 1 int bucketLevel=MAX_BURST; int BUCKET_SIZE= MAX_BURST; int PACKET_SIZE=1; /* one char per "packet" going to the screen */ int fillingRate= FILL_RATE; /* 1 byte per second */ pthread_mutex_t bucketLock = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t bucketChange = PTHREAD_COND_INITIALIZER; void * fillBucket(void * arg) { while (1) { /* we could wait for bucket not full using another * conditional variable*/ sleep(1); pthread_mutex_lock(&bucketLock); if (bucketLevel+fillingRate < BUCKET_SIZE) bucketLevel+=fillingRate; 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, fillBucket, NULL); if (err != 0){ printf("can't create thread \n"); exit(0); } c = getchar(); while (c!=EOF) { pthread_mutex_lock(&bucketLock); while ( bucketLevel < PACKET_SIZE) /* while bucket is almost empty */ pthread_cond_wait(&bucketChange, &bucketLock); bucketLevel-=PACKET_SIZE; pthread_mutex_unlock(&bucketLock); putchar(c); fflush(stdout); c = getchar(); } exit(0); }