单生产者 多消费者

#include <sys/wait.h>
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <pthread.h>
#include <semaphore.h>

sem_t sem_filled;
sem_t sem_empty;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
    
int head = 0;
int tail = 0;
char loop_buf[10][100];

int pipefd[2];

void *printf_thread()
{
//char buf[100];
while(1){
//read(pipefd[0],buf,sizeof(buf));
//printf("~~~ read is %s\n",buf);
int sval;
sem_getvalue(&sem_empty, &sval);
printf("sem_empty value is %d   ",sval);
sem_wait(&sem_filled);
pthread_mutex_lock(&mutex);
printf("                   11  ~~~~~~~read is %s\n",loop_buf[tail]);
tail = tail+1 > 9 ? 0 : tail+1;
pthread_mutex_unlock(&mutex);
sem_post(&sem_empty);
//sleep(2);
}
}


void *printf_thread2()
{
//char buf[100];
while(1){
//read(pipefd[0],buf,sizeof(buf));
//printf("~~~ read is %s\n",buf);
int sval;
sem_getvalue(&sem_empty, &sval);
printf("sem_empty value is %d  ",sval);
sem_wait(&sem_filled);
pthread_mutex_lock(&mutex);
printf("                    22 ~~~~~~~read is %s\n",loop_buf[tail]);
tail = tail+1 > 9 ? 0 : tail+1;
pthread_mutex_unlock(&mutex);
sem_post(&sem_empty);
//sleep(2);
}
}


void *printf_thread3()
{
//char buf[100];
while(1){
//read(pipefd[0],buf,sizeof(buf));
//printf("~~~ read is %s\n",buf);
int sval;
sem_getvalue(&sem_empty, &sval);
printf("sem_empty value is %d   ",sval);
sem_wait(&sem_filled);
pthread_mutex_lock(&mutex);
printf("                    33 ~~~~~~~read is %s\n",loop_buf[tail]);
tail = tail+1 > 9 ? 0 : tail+1;
pthread_mutex_unlock(&mutex);
sem_post(&sem_empty);
//sleep(2);
}
}


int
main(int argc, char *argv[])
{
   
   //pid_t cpid;
    int i = 0;   

   //if (pipe(pipefd) == -1) {
   //    perror("pipe");
   //    exit(EXIT_FAILURE);
   //}
int sval;
sem_init(&sem_empty,0,9);
sem_init(&sem_filled,0,0);

//sem_getvalue(&g_sem, &sval);
//printf("sem value is %d\n",sval);

pthread_t threadid;
pthread_create(&threadid,NULL,printf_thread,NULL);
pthread_create(&threadid,NULL,printf_thread2,NULL);
pthread_create(&threadid,NULL,printf_thread3,NULL);

char buf[100];
while(i<200){

//gets(buf);
//write(pipefd[1],buf,sizeof(buf));
sem_getvalue(&sem_empty, &sval);
printf("sem_empty value is %d   ",sval);
i++;
sprintf(buf,"%d",i);
if(!sem_trywait(&sem_empty)){
printf("@insert is %s\n",buf);
strcpy(loop_buf[head],buf);
head = head+1 > 9 ? 0 : head+1;
sem_post(&sem_filled);
}else{
printf("!!!!lose  %s\n",buf);
}

//usleep(1);

}

while(1)sleep(2);

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值