sd

来源:互联网 发布:js注释写法 编辑:程序博客网 时间:2024/04/30 11:55
#include<semaphore.h>
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<errno.h>
#include<stdlib.h>
struct Product{
int num;
struct Product *next;
};
struct Product *head;


int main(){
sem_t sem;
if(sem_init(&sem,1,1)<0){
perror("sem init error");
exit(0);
}


struct Product *p;
int i=fork(),loop=10,k;
printf("i=%d\n",i);
//child Customer
if(i==0){
for(k=0;k<loop;k++){
sem_wait(&sem);
/*if(head==NULL)
sleep(3);
*/
p=head;
head=p->next;
printf("sell one NO.%d\n",p->num);
sem_post(&sem);
}
exit(0);
}
//parent producer
for(k=0;k<loop;k++){
sem_wait(&sem);
p=malloc(sizeof(struct Product));
p->num=rand()%1000+1;
p->next=head;
head=p;
printf("produce one NO.%d\n",p->num);
sem_post(&sem);
sleep(1);
}
exit(0);
}
0 0
原创粉丝点击