#include #include #include #include #include #include /* buffer of downloaded data */ char download_buffer[512]; sem_t download_empty; sem_t download_full; /* buffer of decompressed data */ char decompress_buffer[512]; sem_t decompress_empty; sem_t decompress_full; /* when to quit the program */ volatile int quit = 0; /* the function called for the first thread, downloading the video frames */ void* download(void* p) { /* loop forever */ while (!quit) { /* wait until the buffer is empty */ sem_wait(&download_empty); /* fill it with data (really just a string from stdin) */ scanf("%s", download_buffer); /* if EOF, quit */ if (feof(stdin)) { quit = 1; } /* tell the decompress that it's full */ sem_post(&download_full); } return NULL; } /* the function called for the second thread, decompressing the video */ void* decompress(void* p) { /* loop forever */ while (!quit) { /* wait for the download buffer to be full */ sem_wait(&download_full); /* wait for the decompress buffer to be empty */ sem_wait(&decompress_empty); /* move from download buffer to decompress */ strcpy(decompress_buffer, download_buffer); /* tell download thread the buffer is empty */ sem_post(&download_empty); /* capitalize it */ int i; for (i = 0; i < strlen(decompress_buffer); i++) { decompress_buffer[i] = toupper(decompress_buffer[i]); } /* tell display thread the buffer is full */ sem_post(&decompress_full); } return NULL; } /* the function called for the third thread, displaying the video */ void* display(void* p) { /* loop forever */ while (!quit) { /* wait for the decompress buffer to be full */ sem_wait(&decompress_full); /* display it */ printf("%s\n", decompress_buffer); /* tell the thread it's empty */ sem_post(&decompress_empty); } return NULL; } int main() { /* the threads */ pthread_t a, b, c; /* setup the semaphores to show all buffers empty */ sem_init(&download_empty, 0, 1); sem_init(&download_full, 0, 0); sem_init(&decompress_empty, 0, 1); sem_init(&decompress_full, 0, 0); /* spawn all threads */ pthread_create(&a, NULL, download, NULL); pthread_create(&b, NULL, decompress, NULL); pthread_create(&c, NULL, display, NULL); /* join all threads */ pthread_join(a, NULL); pthread_join(b, NULL); pthread_join(c, NULL); return 0; }