fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <pthread.h>
  4. #include <unistd.h>
  5. #include <time.h>
  6. #define N 5
  7. int stack[N];
  8. int top = -1;
  9. pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
  10. pthread_cond_t full = PTHREAD_COND_INITIALIZER;
  11. pthread_cond_t empty = PTHREAD_COND_INITIALIZER;
  12. int c = 0;
  13. void* producer(void* arg);
  14. void* consumer(void* arg);
  15. int main()
  16. {
  17. pthread_t producer_thread, consumer_thread;
  18. pthread_create(&producer_thread, NULL, producer, NULL);
  19. pthread_create(&consumer_thread, NULL, consumer, NULL);
  20. pthread_join(producer_thread, NULL);
  21. pthread_join(consumer_thread, NULL);
  22. return 0;
  23. }
  24. void* producer(void* arg)
  25. {
  26. srand(time(NULL));
  27. while (1)
  28. {
  29. pthread_mutex_lock(&mutex);
  30. if (c == 2 * N)
  31. {
  32. pthread_mutex_unlock(&mutex);
  33. break;
  34. }
  35. int num = rand() % 100 + 1;
  36. if (num % 2 != 0)
  37. {
  38. while (top == N - 1)
  39. {
  40. pthread_cond_wait(&full, &mutex);
  41. }
  42. top++;
  43. stack[top] = num;
  44. printf("Producer added %d to the stack\n", num);
  45. pthread_cond_signal(&empty);
  46. c++;
  47. }
  48. pthread_mutex_unlock(&mutex);
  49. sleep(1);
  50. }
  51. return NULL;
  52. }
  53. void* consumer(void* arg)
  54. {
  55. srand(time(NULL));
  56. while (1)
  57. {
  58. pthread_mutex_lock(&mutex);
  59. if (c == 2 * N)
  60. {
  61. pthread_mutex_unlock(&mutex);
  62. break;
  63. }
  64. int num = rand() % 100 + 1;
  65. if (num % 2 == 0)
  66. {
  67. while (top == -1)
  68. {
  69. pthread_cond_wait(&empty, &mutex);
  70. }
  71. int item = stack[top];
  72. top--;
  73. printf("Consumer removed %d from the stack\n", item);
  74. pthread_cond_signal(&full);
  75. c++;
  76. }
  77. pthread_mutex_unlock(&mutex);
  78. sleep(1);
  79. }
  80. return NULL;
  81. }
Success #stdin #stdout 0.01s 5292KB
stdin
Standard input is empty
stdout
Producer added 33 to the stack
Consumer removed 33 from the stack
Producer added 61 to the stack
Consumer removed 61 from the stack
Producer added 13 to the stack
Consumer removed 13 from the stack
Producer added 89 to the stack
Consumer removed 89 from the stack
Producer added 85 to the stack
Consumer removed 85 from the stack