Chinaunix首页 | 论坛 | 博客
  • 博客访问: 247894
  • 博文数量: 45
  • 博客积分: 802
  • 博客等级: 军士长
  • 技术积分: 470
  • 用 户 组: 普通用户
  • 注册时间: 2010-10-08 12:21
文章分类
文章存档

2014年(4)

2013年(4)

2012年(37)

我的朋友

分类: C/C++

2012-01-07 12:01:16

 

  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. #include<semaphore.h>
  4. #include<pthread.h>

  5. #define STORAGE_SIZE 5
  6. #define PRODUCER_SPEED 2//模拟IO
  7. #define CONSUMER_SPEED 1//模拟CPU预处理

  8. char buff[STORAGE_SIZE];
  9. sem_t full_sem, empty_sem;
  10. void *producer(void *arg){
  11. int index = 0;//指向当前要放入的位置

  12. while(1){

  13. sem_wait(&empty_sem);//P
  14. buff[index]= 'a';
  15. printf("produce a food: a at %d\n", index);
  16. index = (index + 1) % STORAGE_SIZE;
  17. sem_post(&full_sem);//V
  18. sleep(PRODUCER_SPEED);
  19. }
  20. }
  21. void *consumer(void *arg){
  22. int index = 0;//指向当前要消费的位置
  23. while(1){
  24. sem_wait(&full_sem);//P
  25. buff[index] = '\0';
  26. printf("consume a food: a at %d\n", index);
  27. index = (index + 1) % STORAGE_SIZE;
  28. sem_post(&empty_sem);//V
  29. sleep(CONSUMER_SPEED);
  30. }
  31. }

  32. int main(){

  33. pthread_t tid_p, tid_c;
  34. sem_init(&full_sem, 0, 0);
  35. sem_init(&empty_sem, 0, 5);

  36. pthread_create(&tid_p, NULL, producer, NULL);
  37. pthread_create(&tid_c, NULL, consumer, NULL);

  38. pthread_join(tid_p, NULL);
  39. pthread_join(tid_c, NULL);
  40. return 0;
  41. }
阅读(1212) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~