pastebin

Paste Search Dynamic
Recent pastes
producer
  1. #include <stdio.h>
  2. #include <pthread.h>
  3. #include <semaphore.h>
  4. #include <time.h>
  5. #include <sys/time.h>
  6. #include <sys/types.h>
  7. #include <unistd.h>
  8. // using namespace std;
  9. const unsigned int N=30;
  10. int buffer[30];
  11. sem_t Empty;
  12. sem_t full;
  13. sem_t s;
  14. int In=0;
  15. int out=0;
  16.  
  17.  
  18. void * producer(void *value)
  19. {
  20.   int val=(int)value;
  21.   //int x = *((int*)(&arg));
  22.   while(val)
  23.   {
  24.  
  25.     sem_wait(&Empty);
  26.     sem_wait(&s);
  27.     buffer[In]=val;
  28.     In=(In+1);
  29.     printf("Produced: %dn" ,val);
  30.     val--;
  31.     usleep(5);
  32.     sem_post(&s);
  33.     sem_post(&full);
  34.  
  35.   }
  36.   return 0;
  37. }
  38.  
  39. void * consumer(void *co){
  40.    int c=(int)co;
  41.   while(c)
  42.   {
  43.  
  44.     sem_wait(&full);
  45.     sem_wait(&s);
  46.     int item=buffer[out];
  47.     out=(out+1);
  48.     // cout<<"consumed: "<<item<<endl;
  49.      printf("consumed: %dn" ,item);
  50.     usleep(5);
  51.     c--;
  52.     sem_post(&s);
  53.     sem_post(&Empty);
  54.  
  55.   }
  56.   return 0;
  57. }
  58.  
  59.  
  60. int main() {
  61.   sem_init(&Empty,0,N);
  62.   sem_init(&full,0,0);
  63.   sem_init(&s,0,1);
  64.   pthread_t cons;
  65.   pthread_t prod;
  66.   pthread_create(&cons,null,consumer,(void*)5);
  67.   pthread_create(&prod,null,producer,(void*)10);
  68.   pthread_join(cons,null);
  69.   pthread_join(prod,null);
  70.  
  71.  
  72.   return 0;
  73. }
Parsed in 0.015 seconds