课后作业
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <IOhead.h>
#include <pthread.h>
#include <semaphore.h>
char buf[]="1234567";
sem_t sem1,sem2;
void* DY(void* arg)
{
while(1)
{
sem_wait(&sem2);
printf("%s\n",buf);
sem_post(&sem1);
}
pthread_exit(NULL);
}
void* NZ(void* arg)
{
int len=strlen(buf);
int b=len;
int i;
while(1)
{
if(sem_wait(&sem1)<0)
{
perror("sem wait");
return NULL;
}
for(i=0;i<len/2+len%2;i++)
{
char t=buf[i];
buf[i]=buf[len-1-i];
buf[len-1-i]=t;
}
i=0;len=b;
if(sem_post(&sem2)<0)
{
perror("sem_post");
return NULL;
}
}
pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
if(sem_init(&sem1,0,0)<0)
{
perror("sem1_init");
return -1;
}
printf("sem1 success\n");
if(sem_init(&sem2,0,1)<0)
{
perror("sem2_init");
return -1;
}
printf("sem2 success\n");
pthread_t tid1;
if(pthread_create(&tid1,NULL,NZ,NULL)!=0)
{
printf("error %d\n",__LINE__);
return -1;
}
pthread_t tid;
if(pthread_create(&tid,NULL,DY,NULL)!=0)
{
printf("error %d\n",__LINE__);
return -1;
}
pthread_join(tid1,NULL);
pthread_join(tid,NULL);
sem_destroy(&sem1);
sem_destroy(&sem2);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <IOhead.h>
#include <pthread.h>
#include <semaphore.h>
char buf;
sem_t sem1,sem2;int fd;int a=0;ssize_t b;
void* SC(void* arg)
{
while(1)
{
if(sem_wait(&sem2)<0)
{
perror("sem wait");
return NULL;
}
if(a)
break;
printf("%c",buf);
if(sem_post(&sem1)<0)
{
perror("sem wait");
return NULL;
}
}
pthread_exit(NULL);
}
void* DQ(void* arg)
{
while(1)
{
if(a)
break;
if(sem_wait(&sem1)<0)
{
perror("sem_post");
return NULL;
}
b=read(fd,&buf,sizeof(buf));
if(b==0)
{
a=1;
if(sem_post(&sem2)<0)
{
perror("sem wait");
return NULL;
}
break;
}
sem_post(&sem2);
}
pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
fd=open("cat.c",O_RDONLY);
if(sem_init(&sem1,0,1)<0)
{
perror("sem1_init");
return -1;
}
printf("sem1 success\n");
if(sem_init(&sem2,0,0)<0)
{
perror("sem2_init");
return -1;
}
printf("sem2 success\n");
pthread_t tid1;
if(pthread_create(&tid1,NULL,DQ,NULL)!=0)
{
printf("error %d\n",__LINE__);
return -1;
}
pthread_t tid;
if(pthread_create(&tid,NULL,SC,NULL)!=0)
{
printf("error %d\n",__LINE__);
return -1;
}
pthread_join(tid1,NULL);
pthread_join(tid,NULL);
sem_destroy(&sem1);
sem_destroy(&sem2);
return 0;
}
思维导图: