IO day7(用线程实现类cat )

 2.创建两个线程,实现将一个文件的内容打印到终端上,类似cat一个文件
一个线程读取文件中的内容
另一个线程将读取到的内容打印到终端上。

#include<stdio.h>
#include<sys/types.h>
#include<unistd.h>
#include<pthread.h>
#include<strings.h>
#include<stdlib.h>
#include<fcntl.h>
#include<sys/stat.h>

struct info
{
	int fp;
	int fw;
	off_t n;
};
char arr;
int flag=1;
pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond=PTHREAD_COND_INITIALIZER;

void* bad1(void * arg)
{

	int fp=((struct info *)arg)->fp;
	off_t n=((struct info *)arg)->n;
	off_t m=n/2;
	off_t offsize=0;
	while(1)
	{
		pthread_mutex_lock(&mutex);

		lseek(fp,offsize,SEEK_SET);

		read(fp,&arr,1);
		if(lseek(fp,0,SEEK_CUR)>n)
		{
			break;
		}
		if(flag!=1)
		{
			pthread_cond_wait(&cond,&mutex);
		}

		offsize=lseek(fp,0,SEEK_CUR);

		flag=0;
		pthread_cond_signal(&cond);	
		pthread_mutex_unlock(&mutex);
	}	

	printf("pick one over\n");
	pthread_exit(NULL);
}

void* bad2(void * arg)
{
	int aa=1,bb=1;

	off_t n=((struct info *)arg)->n;
	off_t m=n/2;
	off_t count=1;
	while(1)
	{
		pthread_mutex_lock(&mutex);

		if(flag!=0)
		{
			pthread_cond_wait(&cond,&mutex);
		}
		printf("%c",arr);

		count++;
		if(count>=n)
		{
			break;
		}
		flag=1;
		pthread_cond_signal(&cond);	
		pthread_mutex_unlock(&mutex);
	}
	pthread_exit(NULL);
}

int main(int argc, const char *argv[])
{

	//	printf("b=%d\n",b);
	int fp=-1,fw=-1;

	fp=open(argv[1],O_RDONLY);
	if(0>fp)
	{
		printf("%d\t",__LINE__);
		perror("open");
		return -1;
	}
	off_t n=lseek(fp,0,SEEK_END);

	struct info file;
	file.fp=fp;
	file.fw=fw;
	file.n=n;

	pthread_t tid1;
	if(pthread_create(&tid1,NULL,bad1,(void *)&file))
	{
		fprintf(stderr,"pthread_creat1 is flase.%d\n",__LINE__);
		return -1;
	}

	pthread_t tid2;
	if(pthread_create(&tid2,NULL,bad2,(void *)&file))
	{
		fprintf(stderr,"pthread_creat2 is flase.%d\n",__LINE__);
		return -1;
	}
	pthread_join(tid2,NULL);
	close(fw);
	close(fp);
	pthread_mutex_destroy(&mutex);

	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值