fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <pthread.h>
  4. #include <semaphore.h>
  5. #include <unistd.h>
  6.  
  7. int *buffer;
  8. int size, in = 0, out = 0;
  9. sem_t empty, full;
  10. pthread_mutex_t mutex;
  11.  
  12. void *producer(void *arg) {
  13. int n, item;
  14. printf("Enter number of items to produce: ");
  15. scanf("%d", &n);
  16. for (int i = 0; i < n; i++) {
  17. printf("Enter item %d to produce: ", i + 1);
  18. scanf("%d", &item);
  19. sem_wait(&empty);
  20. pthread_mutex_lock(&mutex);
  21. buffer[in] = item;
  22. printf("Produced: %d\n", item);
  23. in = (in + 1) % size;
  24. pthread_mutex_unlock(&mutex);
  25. sem_post(&full);
  26. sleep(1);
  27. }
  28. pthread_exit(NULL);
  29. }
  30.  
  31. void *consumer(void *arg) {
  32. int n, item;
  33. printf("Enter number of items to consume: ");
  34. scanf("%d", &n);
  35. for (int i = 0; i < n; i++) {
  36. sem_wait(&full);
  37. pthread_mutex_lock(&mutex);
  38. item = buffer[out];
  39. printf("Consumed: %d\n", item);
  40. out = (out + 1) % size;
  41. pthread_mutex_unlock(&mutex);
  42. sem_post(&empty);
  43. sleep(1);
  44. }
  45. pthread_exit(NULL);
  46. }
  47.  
  48. int main() {
  49. pthread_t prod, cons;
  50. printf("Enter buffer size: ");
  51. scanf("%d", &size);
  52. buffer = malloc(size * sizeof(int));
  53. sem_init(&empty, 0, size);
  54. sem_init(&full, 0, 0);
  55. pthread_mutex_init(&mutex, NULL);
  56. pthread_create(&prod, NULL, producer, NULL);
  57. pthread_create(&cons, NULL, consumer, NULL);
  58. pthread_join(prod, NULL);
  59. pthread_join(cons, NULL);
  60. pthread_mutex_destroy(&mutex);
  61. sem_destroy(&empty);
  62. sem_destroy(&full);
  63. free(buffer);
  64. return 0;
  65. }
  66.  
Success #stdin #stdout 0s 5320KB
stdin
Standard input is empty
stdout
Enter buffer size: Enter number of items to consume: Enter number of items to produce: