在第一题的基础上加上一个需求:要求打印,倒置线程,顺序执行。出现的现象为先打印1234567,后打印7654321
不使用flag
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include<head.h>
#include<pthread.h>
#include<semaphore.h>
sem_t sem1;
char a[]="1234567";
int key=1;
void *xhdy(void *p)
{
while(1)
{
sem_post(&sem1);
printf("%s\n",a);
}
}
void *nizhi(void *p)
{
char t;
int i,j;
while(1)
{
sem_wait(&sem1);
for(i=0;a[i]!='\0';i++);
i=i-1;
j=0;
while(j<i)
{
t=a[i];
a[i]=a[j];
a[j]=t;
j++;
i--;
}
}
}
int main(int argc, const char *argv[])
{
sem_init(&sem1,0,1);
sem_wait(&sem1);
pthread_t tid;
pthread_create(&tid,NULL,xhdy,NULL);
pthread_t tid1;
pthread_create(&tid1,NULL,nizhi,NULL);
pthread_join(tid1,NULL);
pthread_join(tid,NULL);
sem_destroy(&sem1);
return 0;
}
创建两个线程,其中一个线程读取文件中的数据,另外一个线程将读取到的内容打印到终端上,类似实现cat一个文件。
cat数据完毕后,要结束两个线程。
提示:先读数据,读到数据后将数据打印到终端上
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include<head.h>
#include<pthread.h>
#include<semaphore.h>
sem_t sem1,sem2;
char c;
pthread_t fp1,fp2;
size_t size;
void *cocc1(void *p)
{
int fp=open("1.c",O_RDONLY);
while(1)
{
sem_wait(&sem1);
size=read(fp,&c,1);
if(size<=0)
{
close(fp);
sem_post(&sem2);
break;
}
sem_post(&sem2);
}
pthread_exit(fp1);
}
void *cocc2(void *p)
{
while(1)
{
sem_wait(&sem2);
if(size<=0)
{
pthread_exit(fp2);
}
printf("%c",c);
sem_post(&sem1);
}
}
int main(int argc, const char *argv[])
{
sem_init(&sem1,0,1);
sem_init(&sem2,0,0);
pthread_create(&fp1,NULL,cocc1,NULL);
pthread_create(&fp2,NULL,cocc2,NULL);
pthread_join(fp2,NULL);
pthread_join(fp1,NULL);
return 0;
}