Advertisement
Guest User

Untitled

a guest
Nov 24th, 2014
169
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.26 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. #include<pthread.h>
  3. #include<unistd.h>
  4. #define MAX 10
  5. using namespace std;
  6. class BoundedBuffer
  7. {
  8. private:
  9. int buffer[MAX];
  10. int fill, use;
  11. int fullEntries;
  12. pthread_mutex_t monitor; // monitor lock
  13. pthread_cond_t empty;
  14. pthread_cond_t full;
  15. public:
  16. BoundedBuffer ()
  17. {
  18. use = fill = fullEntries = 0;
  19. }
  20. void produce (int element)
  21. {
  22. pthread_mutex_lock (&monitor);
  23. while (fullEntries == MAX)
  24. pthread_cond_wait (&empty, &monitor);
  25. buffer[fill] = element;
  26. fill = (fill + 1) % MAX;
  27. fullEntries++;
  28. //sleep(rand()%2);
  29. pthread_cond_signal (&full);
  30. pthread_mutex_unlock (&monitor);
  31. }
  32. int consume ()
  33. {
  34. pthread_mutex_lock (&monitor);
  35. while (fullEntries == 0)
  36. pthread_cond_wait (&full, &monitor);
  37. int tmp = buffer[use];
  38. use = (use + 1) % MAX;
  39. fullEntries--;
  40. //sleep(rand()%2);
  41. pthread_cond_signal (&empty);
  42. pthread_mutex_unlock (&monitor);
  43. return tmp;
  44. }
  45. }b;
  46. void* producer(void *arg){
  47. int i=1;
  48. while(true){
  49. b.produce(i);
  50. i++;
  51. }
  52. }
  53. void* consumer(void *arg){
  54. while(true){
  55. cout<<b.consume()<<" ";
  56. }
  57. }
  58. int main(){
  59. pthread_t t1,t2;
  60. pthread_create(&t1,NULL,producer,NULL);
  61. pthread_create(&t2,NULL,consumer,NULL);
  62. pthread_join(t1,NULL);
  63. pthread_join(t2,NULL);
  64. return 0;
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement