pv-signal1.c

#include<stdio.h>
#include<pthread.h>
#include <semaphore.h>
#include <unistd.h>
void father();
void daughter();
sem_t empty,app;   //定义信号量empty, app ;
int k=0;   //盘中苹果个数
int main()
{ pthread_t th1,th2;
  int ret;
  sem_init(&empty,0,1);    //初始化线程信号量empty ,初值为1
  sem_init(&app,0,0);    //初始化线程信号量app ,初值为0
  ret=pthread_create(&th1,NULL,(void *) father, NULL);
  if(ret!=0)  perror("pthread cread1");
  ret=pthread_create(&th2,NULL,(void *)daughter, NULL);
  if(ret!=0)  perror("pthread cread2");
  pthread_join(th1,NULL);
  pthread_join(th2,NULL);
  return 0;
}
void father()
{     
    do{
         //执行信号量empty的wait()操作,相当于 wait(empty)
         sem_wait(& empty); 
         printf("I am father\n");
         printf("I am putting an apple in the plate!\n");
         printf("There is  %d fruit in the plate!\n",++k);
        //执行信号量app的signal()操作,相当于 signal(app)
        sem_post(& app); 
  }while(1);
}
void daughter()
{   
 do{
     //执行信号量app的wait()操作,相当于 wait(app)
     sem_wait(&app); 
     printf("I am daughter\n");
    printf("I am picking an apple from the plate!\n");
     printf("There are  %d fruit in the plate!\n",--k);
     //执行信号量empty的signal()操作,相当于signal(empty)
     sem_post(& empty); 
 }while(1);
  }

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值