Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <pthread.h>
- #include <string.h>
- #include <errno.h>
- #include <fcntl.h>
- #include <semaphore.h>
- pthread_mutex_t prod_mutex, cons_mutex;
- pthread_cond_t ready_to_produce =PTHREAD_COND_INITIALIZER;
- pthread_cond_t ready_to_consume =PTHREAD_COND_INITIALIZER;
- #define MAX 5
- int buf[MAX];
- int pid;
- void* prod(void *p){
- int index = 0;
- int i;
- pthread_mutex_lock(&prod_mutex);
- for (i=0;i<100;i++){
- buf[index] = i;
- if (index == 0 && i >= 5)
- {
- pthread_cond_wait(&ready_to_produce, &prod_mutex);
- }
- index = (index + 1) % MAX;
- pthread_mutex_unlock(&prod_mutex);
- if (index == 0)
- {
- pthread_mutex_lock(&cons_mutex);
- pthread_cond_signal(&ready_to_consume);
- pthread_mutex_unlock(&cons_mutex);
- }
- }
- }
- void* kons(void *p){
- int index = 0;
- int i;
- for (i=0;i<100;i++){
- if (index == 0 && i >= 5)
- {
- pthread_cond_wait(&ready_to_consume, &cons_mutex);
- }
- printf("Process %d : %d\n", pid, buf[index]);
- index = (index + 1) % MAX;
- pthread_mutex_unlock(&cons_mutex);
- if ( index == 0)
- {
- pthread_mutex_lock(&prod_mutex);
- pthread_cond_signal(&ready_to_produce);
- pthread_mutex_unlock(&prod_mutex);
- }
- }
- }
- int main(){
- pthread_mutex_init(&prod_mutex, NULL);
- pthread_mutex_init(&cons_mutex, NULL);
- pthread_t pth1, pth2, pth3, pth4;
- pthread_create(&pth1, NULL, prod, NULL);
- pthread_create(&pth2, NULL, prod, NULL);
- pthread_create(&pth3, NULL, kons, NULL);
- pthread_create(&pth4, NULL, kons, NULL);
- pthread_join(pth1, NULL);
- pthread_join(pth2, NULL);
- pthread_join(pth3, NULL);
- pthread_join(pth4, NULL);
- pthread_mutex_destroy(&prod_mutex);
- pthread_mutex_destroy(&cons_mutex);
- pthread_cond_destroy(&ready_to_consume);
- pthread_cond_destroy(&ready_to_produce);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement