在第一题的基础上加上一个需求:要求打印,倒置线程,顺序执行。出现的现象为先打印1234567,后打印7654321
不使用flag
代码:
#include <stdio.h>
#include<string.h>
#include<stdlib.h>
#include <IOhead.h>
#include <semaphore.h>
void *CallBack(void *arg);
void *output(void *arg);
char buf[]="1234567";
sem_t sem1;
sem_t sem2;
int main(int argc, const char *argv[])
{
pthread_t tid1,tid2;
sem_init(&sem1,0,1);
sem_init(&sem2,0,0);
if(pthread_create(&tid1,NULL,CallBack,NULL)!=0)
{ fprintf(stderr,"error __%d__ \n",__LINE__);
return -1;
}
if(pthread_create(&tid2,NULL,output,(void*)&tid1)!=0)
{ fprintf(stderr,"error __%d__ \n",__LINE__);
return -1;
}
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
sem_destroy(&sem1);
sem_destroy(&sem2);
return 0;
}
//逆置
void *CallBack(void *arg)
{
while(1)
{ int i=0;
sem_wait(&sem1);
while(i<strlen(buf)/2)
{
char t=buf[i];
buf[i]=buf[strlen(buf)-i-1];
buf[strlen(buf)-i-1]=t;
i++;
}
sem_post(&sem2);
}
pthread_exit(NULL);
}
//循环输出
void *output(void *arg)
{
while(1)
{
sem_wait(&sem2);
printf("%s\n",buf);
sem_post(&sem1);
}
}
运行结果:
创建两个线程,其中一个线程读取文件中的数据,另外一个线程将读取到的内容打印到终端上,类似实现cat一个文件。
cat数据完毕后,要结束两个线程。
提示:先读数据,读到数据后将数据打印到终端上。
代码:
#include <stdio.h>
#include<string.h>
#include<stdlib.h>
#include <IOhead.h>
#include <pthread.h>
#include <semaphore.h>
sem_t sem1;
sem_t sem2;
int fb_r;
char buf;
ssize_t size;
void *get(void*arg)
{ while(1)
{
sem_wait(&sem1);
size=read(fb_r,&buf,1);
if(size==0)
{ sem_post(&sem2);
return NULL;
}
sem_post(&sem2);
}
pthread_exit(NULL);
}
void *put(void*arg)
{
while(1)
{
sem_wait(&sem2);
if(size==0)
break;
write(1,&buf,1);
sem_post(&sem1);
}
pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
pthread_t tid1,tid2;
sem_init(&sem1,0,1);
sem_init(&sem2,0,0);
fb_r=open("./3.c",O_RDONLY);
if(pthread_create(&tid1,NULL,get,NULL)!=0)
{ fprintf(stderr,"error __%d__ \n",__LINE__);
return -1;
}
if(pthread_create(&tid2,NULL,put,(void*)&tid1)!=0)
{ fprintf(stderr,"error __%d__ \n",__LINE__);
return -1;
}
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
sem_destroy(&sem1);
sem_destroy(&sem2);
return 0;
}
运行结果:
思维导图: