ariestamirra

Semaphore

May 31st, 2014
191
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.49 KB | None | 0 0
  1. #include<stdio.h>
  2. #include<pthread.h>
  3. #include<sys/types.h>
  4. #include<unistd.h>
  5. #include<stdlib.h>
  6. #include<semaphore.h>
  7. #include<windows.h>
  8.  
  9. #define sleep(n) Sleep(n*500)
  10. #define MAX 5
  11.  
  12. sem_t empty,full,mutex;
  13. char buf[MAX];
  14. char character = 'A';
  15.  
  16. void* thread_fun1(void* arg)
  17. {
  18.     int i;
  19.     printf("--------------------\n");
  20.     printf("PRODUCER CONSUMER\nOleh : Mirra Ariesta\n");
  21.     printf("--------------------\n");
  22.     for(i=0; i<MAX; i++){
  23.         sem_wait(&empty);
  24.         sem_wait(&mutex);
  25.         buf[i]=character++;
  26.         printf("item produced is %c\n",buf[i]);
  27.         sem_post(&mutex);
  28.         sem_post(&full);
  29.         sleep(1);
  30.     }
  31.     char* name = "producer\n";
  32.     pthread_exit(name);
  33.  
  34. }
  35. void * thread_fun2(void* arg){
  36.     int j;
  37.  
  38.     for(j=0; j<MAX; j++){
  39.         sem_wait(&full);
  40.         sem_wait(&mutex);
  41.         sleep(1);
  42.         printf("consumed item is:%c\n",buf[j]);
  43.         sem_post(&mutex);
  44.         sem_post(&empty);
  45.         sleep(5);
  46.     }
  47.  
  48.     char* name = "consumer\n";
  49.     pthread_exit(name);
  50. }
  51.  
  52. int main(){
  53.     pthread_t pid1,pid2;
  54.  
  55.     sem_init(&empty,0,MAX);
  56.     sem_init(&full,0,0);
  57.     sem_init(&mutex,1,1);
  58.  
  59.     void *status;
  60.     pthread_create(&pid1,NULL,thread_fun1,NULL);
  61.     pthread_create(&pid2,NULL,thread_fun2,NULL);
  62.  
  63.     pthread_join(pid1,&status);
  64.     printf("the exited status of 1st is %s\n",(char*)status);
  65.     pthread_join(pid2,&status);
  66.     printf("the exited status %s\n",(char*)status);
  67.  
  68.     return 0;
  69. }
Advertisement
Add Comment
Please, Sign In to add comment