sema_pc.cpp 925 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. #include<cstdio>
  2. #include<semaphore.h>
  3. #include<pthread.h>
  4. #include<vector>
  5. #include<cstdlib>
  6. #include<unistd.h>
  7. sem_t full,empty,mutex;
  8. using namespace std;
  9. vector<int>v;
  10. void*producer(void*i)
  11. {
  12. while(true)
  13. {
  14. int temp=rand()%10;
  15. printf("\nproducer produced item %d\n",temp);
  16. sem_wait(&empty);
  17. sem_wait(&mutex);
  18. printf("producer put item %d\n",temp);
  19. v.push_back(temp);
  20. sem_post(&mutex);
  21. sem_post(&full);
  22. }
  23. }
  24. void*consumer(void*i)
  25. {
  26. while(true)
  27. {
  28. sem_wait(&full);
  29. sem_wait(&mutex);
  30. int temp=v.back();
  31. printf("consumer got item %d\n",temp);
  32. v.pop_back();
  33. sem_post(&mutex);
  34. sem_post(&empty);
  35. printf("consumer consumed item %d\n",temp);
  36. }
  37. }
  38. int main()
  39. {
  40. pthread_t prod,cons,i=0;
  41. pthread_create(&prod,NULL,producer,(void*)&i);
  42. pthread_create(&cons,NULL,consumer,(void*)&i);
  43. sem_init(&full,1,0);
  44. sem_init(&empty,1,5);
  45. sem_init(&mutex,1,1);
  46. pthread_join(prod,NULL);
  47. pthread_join(cons,NULL);
  48. }