int main(int argc,char *argv[])
{
int i;
int pid;
int ret;
union semun sem;
sem.val=1;
key_t key=ftok("mem",0);
semid =semget(key,4,IPC_CREAT|0666);
ret=semctl(semid,0,SETVAL,sem);
if(ret==-1)
{
perror("semctl 0:");
}
ret=semctl(semid,1,SETVAL,sem);
if(ret==-1)
{
perror("semct1 0:");
}
ret=semctl(semid,2,SETVAL,sem);
if(ret==-1)
{
perror("semctl 0:");
}
ret=semctl(semid,3,SETVAL,sem);
if(ret==-1)
{
perror("semct1 0:");
}
int j;
for(j=0;j<10;j++)
{
mn[j]=j+1;
}
printf("the original sequence is :\n");
for(j=-0;j<10;j++)
{
printf("%d",mn[j]);
}
printf("\n");
char c;
while(1)
{
printf("r/w:");
scanf("%s",&c);
if(c=='w')
{
if(wc==WN&&rc!=RN)
printf("writers are finished.\n");
else
{
pthread_create(&Writers[wc],NULL,(void*)writer,(void*)(wc+1));
wc++;
sleep(3);
}
}
else if(c=='r')
{
if(rc==RN&&wc!=WN)
printf("readers are finished.\n");
else
{
for(rc=0;rc<RN;rc++)
{
pthread_create(&Readers[rc],NULL,(void*)reader,(void*)(rc+1));
sleep(3);
}
}
}
else
printf("you input a wrong choice ,try again:\n");
if(wc==WN&&rc==RN)
{
printf("All writers and readers are finished.\n");
exit(0);
}
}
semctl(semid,IPC_RMID,0);
return 0;
}
{
int i;
int pid;
int ret;
union semun sem;
sem.val=1;
key_t key=ftok("mem",0);
semid =semget(key,4,IPC_CREAT|0666);
ret=semctl(semid,0,SETVAL,sem);
if(ret==-1)
{
perror("semctl 0:");
}
ret=semctl(semid,1,SETVAL,sem);
if(ret==-1)
{
perror("semct1 0:");
}
ret=semctl(semid,2,SETVAL,sem);
if(ret==-1)
{
perror("semctl 0:");
}
ret=semctl(semid,3,SETVAL,sem);
if(ret==-1)
{
perror("semct1 0:");
}
int j;
for(j=0;j<10;j++)
{
mn[j]=j+1;
}
printf("the original sequence is :\n");
for(j=-0;j<10;j++)
{
printf("%d",mn[j]);
}
printf("\n");
char c;
while(1)
{
printf("r/w:");
scanf("%s",&c);
if(c=='w')
{
if(wc==WN&&rc!=RN)
printf("writers are finished.\n");
else
{
pthread_create(&Writers[wc],NULL,(void*)writer,(void*)(wc+1));
wc++;
sleep(3);
}
}
else if(c=='r')
{
if(rc==RN&&wc!=WN)
printf("readers are finished.\n");
else
{
for(rc=0;rc<RN;rc++)
{
pthread_create(&Readers[rc],NULL,(void*)reader,(void*)(rc+1));
sleep(3);
}
}
}
else
printf("you input a wrong choice ,try again:\n");
if(wc==WN&&rc==RN)
{
printf("All writers and readers are finished.\n");
exit(0);
}
}
semctl(semid,IPC_RMID,0);
return 0;
}