艾尔猫粮好吗:信号量2

来源:百度文库 编辑:偶看新闻 时间:2024/04/28 20:07:23

#include
#include
#include
#include
#include
#include
#include
#include
#define MAXSEM 5
int fullid;
int emptyid;
int mutxid;

int main()
{
 struct sembuf P,V;
 union semun arg;
 int *array;
 int *sum; 
 int *set;
 int *get;
 /*map array,sum,set and get to shared memory*/
 array=(int *)shmat(shmget(IPC_PRIVATE,sizeof(int)*MAXSEM,IPC_CREAT|0666),0,0);
 sum=(int *)shmat(shmget(IPC_PRIVATE,sizeof(int),IPC_CREAT|0666),0,0);
 set=(int *)shmat(shmget(IPC_PRIVATE,sizeof(int),IPC_CREAT|0666),0,0);
 get=(int *)shmat(shmget(IPC_PRIVATE,sizeof(int),IPC_CREAT|0666),0,0);
 *get=0;
 /*create sem fullid,emptyid and mutxid*/
 fullid = semget(IPC_PRIVATE,1,IPC_CREAT|IPC_EXCL|0666);
 emptyid = semget(IPC_PRIVATE,1,IPC_CREAT|0666);
 mutxid = semget(IPC_PRIVATE,1,IPC_CREAT|0666);
 arg.val = 0;
 if(semctl(fullid,0,SETVAL,arg)==-1)
  perror("semctl setval error");
 arg.val = MAXSEM;
 if(semctl(emptyid,0,SETVAL,arg)==-1)
  perror("semctl setval error");
 arg.val = 1;
 if(semctl(mutxid,0,SETVAL,arg)==-1)
  perror("setctl setval error");
 /*init P,V operation*/
 P.sem_num = 0;
 P.sem_op = -1;
 P.sem_flg = SEM_UNDO;
 V.sem_num = 0;
 V.sem_op = 1;
 V.sem_flg = SEM_UNDO;
 if(fork()==0){
  int i =0;
  *set=0;
  while(i<100){
   /*P emptyid,mutxid*/
   semop(emptyid,&P,1);
   semop(mutxid,&P,1);
   array[*(set)%MAXSEM]=i+1;
   (*set)++;
   /*V fullid,mutxid*/
   semop(mutxid,&V,1);
   semop(fullid,&V,1);
   i++;
  }
  sleep(3);
  printf("Proclucer is Over!\n");
  //exit(0);
 }else{
  if(fork()==0){
   while(1){
    /*P fullid,mutxid*/
    semop(fullid,&P,1);
    semop(mutxid,&P,1);
    if(*get == 100)
     break;
    *sum += array[(*get)%MAXSEM];
    printf("The ComsumerA Get Number %d\n",array[(*get)%MAXSEM]);
    (*get)++;
    if((*get) == 100){
     printf("The sum is %d\n",*sum);
     printf("ComsumeB is over!\n");
    }
    /*V emptyid,mutxid*/
    semop(mutxid,&V,1);
    semop(emptyid,&V,1);    
    sleep(1);
   }
   //printf("ComsumeA is Over!\n");
   return 0;
  }else{
   if(fork()==0){
    while(1){
     /*P fullid,mutxid*/
     semop(fullid,&P,1);
     semop(mutxid,&P,1);
     if(*get == 100)
      break;
     *sum += array[(*get)%MAXSEM];
     printf("The ComsumerB Get Number %d\n",array[(*get)%MAXSEM]);
     (*get)++;
     if((*get) == 100){
      printf("The sum is %d\n",*sum);
      printf("ComsumeB is over!\n");
     }  
     /*V emptyid,mutxid*/
     semop(mutxid,&V,1);
     semop(emptyid,&V,1);     
     sleep(1);
    }
    //printf("ComsumeB is over!\n");
    return 0;
   }
  }
 }
 return 0;
}