在第一题的基础上加上一个需求:要求打印,倒置线程,顺序执行。出现的现象为先打印1234567,后打印7654321(不使用flag)
创建两个线程,其中一个线程读取文件中的数据,另外一个线程将读取到的内容打印到终端上,类似实现cat一个文件。
cat数据完毕后,要结束两个线程。
提示:先读数据,读到数据后将数据打印到终端上。
1.
#include<stdio.h>
#include<head.h>
char buf[]="1234567";
sem_t sem1,sem2;
void *myprintf(void *arg)
{int count=0;while(1){if(sem_wait(&sem1)<0)//p操作{ERR_MSG("sem_wait");return NULL;}printf("%s\n",buf);if(sem_post(&sem2)<0)//v操作{ERR_MSG("sem_post");return NULL;}} pthread_exit(NULL);
}
void *strrev(void *arg)
{char t;while(1){if(sem_wait(&sem2)<0)//p操作{ERR_MSG("sem_wait");return NULL;}for(int i=0;i<strlen(buf)/2;i++){t=buf[i];buf[i]=buf[strlen(buf)-1-i];buf[strlen(buf)-1-i]=t;}if(sem_post(&sem1)<0)//v操作{ERR_MSG("sem_post");return NULL;}}pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{if(sem_init(&sem1,0,1)<0){ERR_MSG("sem_inti");return -1;}if(sem_init(&sem2,0,0)<0){ERR_MSG("sem_inti");return -1;}pthread_t tid1,tid2;if(pthread_create(&tid1,NULL,myprintf,NULL)!=0){fprintf(stderr,"pthread_create failed __%d__\n",__LINE__);return -1;}if(pthread_create(&tid2,NULL,strrev,NULL)!=0){fprintf(stderr,"pthread_create failed __%d__\n",__LINE__);return -1;}pthread_join(tid2,NULL);sem_destroy(&sem1);sem_destroy(&sem2);return 0;
}
2.
#include<stdio.h>
#include<head.h>
char c;
ssize_t res;
sem_t sem1,sem2;
void *myread(void *arg)
{int fp=open("ABC.c",O_RDONLY);if(fp<0){ERR_MSG("open");return NULL;}while(1){if(sem_wait(&sem1)<0){ERR_MSG("sem_wait");return NULL;} res=read(fp,&c,1); if(0==res){if(sem_post(&sem2)<0){ERR_MSG("sem_post");return NULL;}break;}if(sem_post(&sem2)<0){ERR_MSG("sem_post");return NULL;}}
}
void *mywrite(void *arg)
{while(1){if(sem_wait(&sem2)<0){ERR_MSG("sem_wait");return NULL;}write(1,&c,res);if(0==res){if(sem_post(&sem1)<0){ERR_MSG("sem_post");return NULL;}break;}if(sem_post(&sem1)<0){ERR_MSG("sem_post");return NULL;}}
}
int main(int argc, const char *argv[])
{if(sem_init(&sem1,0,1)<0){ERR_MSG("sem init"); return -1;}if(sem_init(&sem2,0,0)<0){ERR_MSG("sem init");return -1;}pthread_t tid1,tid2;if(pthread_create(&tid1,NULL,myread,NULL)!=0){fprintf(stderr,"pthread_create failed __%d__\n",__LINE__);return -1;}if(pthread_create(&tid2,NULL,mywrite,NULL)!=0){fprintf(stderr,"pthread_create failed __%d__\n",__LINE__);return -1;}pthread_join(tid1,NULL);pthread_join(tid2,NULL);sem_destroy(&sem1);sem_destroy(&sem2);return 0;
}