Chinaunix首页 | 论坛 | 博客
  • 博客访问: 128020
  • 博文数量: 30
  • 博客积分: 972
  • 博客等级: 中士
  • 技术积分: 332
  • 用 户 组: 普通用户
  • 注册时间: 2012-02-08 10:04
文章分类

全部博文(30)

文章存档

2012年(30)

分类: LINUX

2012-06-21 18:59:20


 

点击(此处)折叠或打开

  1. /* ************************************************************************
  2.  * Filename: proj.c
  3.  * Description:
  4.  * Version: 1.0
  5.  * Created: 2012年06月21日 17时17分24秒
  6.  * Revision: none
  7.  * Compiler: gcc
  8.  * Author: YOUR NAME (),
  9.  * Company:
  10.  * ************************************************************************/
  11. #include <stdlib.h>
  12. #include <semaphore.h>
  13. #include <pthread.h>
  14. #include <unistd.h>
  15. #include <stdio.h>
  16. #define P_TIME 1
  17. #define C_TIME 3
  18. pthread_mutex_t mutex;
  19. sem_t sem_p,sem_c;
  20. pthread_t tid_p,tid_r;
  21. int count=4;
  22. int make(void)
  23. {
  24.  pthread_mutex_lock(&mutex);
  25.  if(pthread_self() == tid_p)
  26.  {
  27.   count++;
  28.   printf("pop in!,the store=%d\n",count);
  29.   //sleep(10);
  30.  }
  31.  else if(pthread_self() == tid_r)
  32.  {
  33.   count--;
  34.   printf("pop out!,the store=%d\n",count);
  35.   //sleep(R_TIME);
  36.  }
  37.  pthread_mutex_unlock(&mutex);
  38.  return 0;
  39. }
  40. void * handler_p(void *a)
  41. {
  42.  while(1)
  43.  {
  44.  sem_wait(&sem_p);
  45.  sleep(P_TIME);
  46.  make();
  47.  //sleep(P_TIME);
  48.  sem_post(&sem_c);
  49.  //sleep(P_TIME);
  50.  }
  51. }
  52. void * handler_c(void *a)
  53. {
  54.  while(1)
  55.  {
  56.  sem_wait(&sem_c);
  57.  make();
  58.  //sleep(C_TIME);
  59.  sem_post(&sem_p);
  60.  sleep(C_TIME);
  61.  }
  62. }
  63. int main(int argc, char *argv[])
  64. {
  65.  //pthread_t tid_p,tid_r;
  66.  sem_init(&sem_p,0,6);
  67.  sem_init(&sem_c,0,4);
  68.  pthread_create(&tid_p,NULL,handler_p,NULL);
  69.  pthread_create(&tid_r,NULL,handler_c,NULL);
  70.  pthread_join(tid_p,NULL);
  71.  pthread_join(tid_r,NULL);
  72.  return 0;
  73. }


 

阅读(1374) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~