首页 > 编程语言 > 详细

linux c++(线程 & 信号量 & 生产者消费者模型)

时间:2021-05-08 00:38:28      阅读:14      评论:0      收藏:0      [点我收藏+]

生产者和消费者模型

信号量[加强版的互斥锁]

  • int sem_init(setm_t *sem,int pshared,unsigned int valud);
    • sem 定义的信号量,传出
    • pshared
      • 0 代表线程信号量
      • 非0 代表进程信号量
    • value 定义信号量的个数
  • 摧毁信号量
    • int sem_destory(sem_t *sem);
  • 申请信号量,申请成功 value--
    - int sem_wait(sem_t *sem);
    • 信号量为0时,阻塞
  • 释放信号量value++
    • int sem_post(sem_t *sem);

  #include <semaphore.h>                                                            
  sem_t blank,xfull;
  #define  __SEM_CNT__ 5
  
  int queue[__SEM_CNT__];
  int beginnum = 100;
  
? void * thr_producter(void *arg)
  {   
      int i = 0;
      while(1)
      {   
          sem_wait(&blank);//申请资源 blank--
          printf("----%s----self---%lu----%d\n",__FUNCTION__,pthread_self(),beginnum
          queue[(i++)%__SEM_CNT__] = beginnum++;
          sem_post(&xfull);//xfull ++
          sleep(rand()%3);
      }
      pthread_exit(NULL);
  }
  // 创建线程 #include <pthread.h>
? void * thr_custmer(void *arg)
  {   
      int i = 0,num = 0;
      while(1)
      {   
          sem_wait(&xfull);
          num = queue[(i++)%__SEM_CNT__];
          printf("----%s----self---%lu----%d\n",__FUNCTION__,pthread_self(),num);
          sem_post(&blank);
          sleep(rand()%3);
      }
      pthread_exit(NULL);
  }
   int main()
  {
      sem_init(&blank,0,__SEM_CNT__);
      sem_init(&xfull,0,0);
      
      pthread_attr_t attr;
      pthread_attr_init(&attr);
      pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED);
      pthread_t tid[2];
      pthread_create(&tid[0],&attr,thr_producter,NULL);
      pthread_create(&tid[1],&attr,thr_custmer,NULL);
      pthread_attr_destroy(&attr);
      pthread_exit(NULL);
  
      sem_destroy(&blank);
      sem_destroy(&xfull);
  
      return 0;
  }

linux c++(线程 & 信号量 & 生产者消费者模型)

原文:https://www.cnblogs.com/lodger47/p/14742054.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!