Created
April 9, 2014 21:27
-
-
Save gtke/10318735 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
pthread_mutex_t buffer_mutex = PTHREAD_MUTEX_INITIALIZER; | |
pthread_cond_t buffer_full = PTHREAD_COND_INITIALIZER; | |
pthread_cond_t buffer_empty = PTHREAD_COND_INITIALIZER; | |
int buffer[10]; | |
void buffer_init(void) | |
{ | |
/* printf("buffer_init called: buffer initialized with ten 0s\n"); */ | |
int i = 0; | |
for(i=0; i<10; i++) buffer[i] = 0; | |
} | |
void buffer_insert(int number) | |
{ | |
int i = 0; | |
pthread_mutex_lock( &buffer_mutex ); | |
while (i < 10 && buffer[i] != 0){ | |
i++; | |
} | |
if (i == 10){ | |
/* printf("buffer_insert called with %d: it's full, waiting \n", number); */ | |
pthread_cond_wait( &buffer_full, &buffer_mutex); | |
i = 0; | |
while (i < 10 && buffer[i] != 0){ | |
i++; | |
} | |
} | |
buffer[i] = number; | |
pthread_cond_signal( &buffer_empty ); | |
/* printf("buffer_insert called with %d: inserted into %d \n", number, i); */ | |
pthread_mutex_unlock ( &buffer_mutex ); | |
} | |
int buffer_extract(void) | |
{ | |
int i = 0; | |
int return_val = 0; | |
pthread_mutex_lock( &buffer_mutex ); | |
while (i < 10 && buffer[i] == 0){ | |
i++; | |
} | |
if (i == 10){ | |
/* printf("buffer_remove called: it's empty, waiting \n"); */ | |
pthread_cond_wait( &buffer_empty, &buffer_mutex); | |
i = 0; | |
while (i < 10 && buffer[i] == 0){ | |
i++; | |
} | |
} | |
return_val = buffer[i]; | |
buffer[i] = 0; | |
pthread_cond_signal( &buffer_full ); | |
/* printf("buffer_extract called: returning %d\n", return_val); */ | |
pthread_mutex_unlock ( &buffer_mutex ); | |
return(return_val); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment