fork download
  1. #include <stdio.h>
  2. #include <pthread.h>
  3. #include <semaphore.h>
  4.  
  5. sem_t empty, full;
  6. int buffer = 0;
  7.  
  8. void *producer(void *arg) {
  9. int item = 1;
  10. sem_wait(&empty);
  11. buffer = item;
  12. printf("生产者生产:%d\n", buffer);
  13. sem_post(&full);
  14. return NULL;
  15. }
  16.  
  17. void *consumer(void *arg) {
  18. sem_wait(&full);
  19. printf("消费者消费:%d\n", buffer);
  20. buffer = 0;
  21. sem_post(&empty);
  22. return NULL;
  23. }
  24.  
  25. int main() {
  26. sem_init(&empty, 0, 1);
  27. sem_init(&full, 0, 0);
  28. pthread_t p, c;
  29. pthread_create(&p, NULL, producer, NULL);
  30. pthread_create(&c, NULL, consumer, NULL);
  31. pthread_join(p, NULL);
  32. pthread_join(c, NULL);
  33. sem_destroy(&empty);
  34. sem_destroy(&full);
  35. return 0;
  36. }
Success #stdin #stdout 0s 5316KB
stdin
Standard input is empty
stdout
生产者生产:1
消费者消费:1