信号量実現の生産者と消費者モデル

12663 ワード

信号量実現の生産者と消費者モデル
  1 #include <stdio.h>
  2 #include <unistd.h>
  3 #include <pthread.h>
  4 #include <semaphore.h>
  5 #include <stdlib.h>
  6 
  7 
  8 sem_t blank, xfull;
  9 #define _SEM_CNT_ 5
 10 
 11 int queue[_SEM_CNT_];//    ,  
 12 int beginnum = 100;
 13 
 14 void* thr_producer(void* arg)
 15 {
     
 16     int i = 0;
 17     while(1){
     
 18         sem_wait(&blank);//    blank--
 19         printf("--%s---self--%lu---num--%d
"
,__FUNCTION__,pthread_self(),beginnum); 20 queue[(i++)%_SEM_CNT_] = beginnum++; 21 sem_post(&xfull);//xfull++ 22 sleep(rand()%3); 23 } 24 return NULL; 25 } 26 27 void* thr_customer(void* arg) 28 { 29 int i = 0; 30 int num = 0; 31 while(1){ 32 sem_wait(&xfull);//xfull-- 33 num = queue[(i++)%_SEM_CNT_]; 34 printf("--%s---self--%lu---num--%d
"
,__FUNCTION__,pthread_self(),num); 35 sem_post(&blank);//blank++ 36 sleep(rand()%3); 37 } 38 39 return NULL; 40 } 41int main(){ 43 sem_init(&blank,0,_SEM_CNT_); 44 sem_init(&xfull,0,0); // 45 46 pthread_t tid[2]; 47 48 pthread_create(&tid[0],NULL,thr_producer,NULL); 49 pthread_create(&tid[1],NULL,thr_customer,NULL); 50 51 pthread_join(tid[0],NULL); 52 pthread_join(tid[1],NULL); 53 54 sem_destroy(&blank); 55 sem_destroy(&xfull); 56 return 0; 57 } 57,1 Bot