IO DAY 7

 

在第一题的基础上加上一个需求:要求打印,倒置线程,顺序执行。出现的现象为先打印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;
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值