example2.c 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. #include "example2.h"
  2. void * produce(void *buf)
  3. {
  4. buffer *buff;
  5. buff = (buffer *)buf;
  6. printf("\nproducer started");
  7. for (int i=0;i<20;i++)
  8. {
  9. sem_wait(&buff->full);
  10. pthread_mutex_lock(&buff->mutex);
  11. buff->data[buff->pos] = 0;
  12. buff->pos = buff->pos + 1;
  13. printf("\nproduced");
  14. sem_post(&buff->empty);
  15. pthread_mutex_unlock(&buff->mutex);
  16. sleep(1);
  17. }
  18. pthread_exit(0);
  19. }
  20. void * consume(void *buf)
  21. {
  22. buffer * buff;
  23. buff = (buffer *)buf;
  24. printf("\nconsumer started");
  25. for (int i=0;i<20;i++)
  26. {
  27. sem_wait(&buff->empty);
  28. pthread_mutex_lock(&buff->mutex);
  29. buff->pos = buff->pos - 1;
  30. printf("\ngot value %d", buff->data[buff->pos]);
  31. printf("\nconsumed");
  32. sem_post(&buff->full);
  33. pthread_mutex_unlock(&buff->mutex);
  34. sleep(2);
  35. }
  36. pthread_exit(0);
  37. }
  38. void init_buffer(buffer *buf)
  39. {
  40. sem_init(&buf->empty, 0, 0);
  41. sem_init(&buf->full, 0, BUFFER_SIZE);
  42. pthread_mutex_init(&buf->mutex, NULL);
  43. buf->pos = 0;
  44. for (int i=0; i<BUFFER_SIZE;i++){
  45. buf->data[i] = -1;
  46. }
  47. }