example2.c 1.0 KB

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