用线程实现cat函数

作业需求:

1.要求创建两个线程,实现文件打印到终端上,类似cat一个文件:

a.A线程读取文件中的内容 A.A线程读取文件中的内容

b.B线程将A线程中读取到的数据打印到终端上c.当文件打印完毕后,结束进程。 

#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <string.h>
#include <semaphore.h>
//临界资源
char str[10]="";
sem_t sem,sem1;
ssize_t res;
int fp;
void *partA(void *arg)
{

	while(1)
	{
		/*********临界区*********/
		sem_wait(&sem);
		res=read(fp,str,sizeof(str));
	
		sem_post(&sem1);

		/*********临界区*********/
			if(res<1)
		{
			break;
		}
	}

	return NULL;

}

void *partB(void *arg)
{
	
	while(1)
	{
		/*********临界区*********/
		
		sem_wait(&sem1);

		write(1,str,res);

		sem_post(&sem);
	/*********临界区*********/
		if(res<1)
		{
			break;
		}
	
	}

	return NULL;

}

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



	 fp=open("./sem.c",O_RDONLY);
	//创建一个分支线程
	pthread_t tid;

	pthread_t tid1;


	//创建一个信号量
	sem_init(&sem,0,1);
	sem_init(&sem1,0,0);


	
		if(pthread_create(&tid,NULL,partA,NULL) != 0)
		{
			fprintf(stderr,"pthread_create falled\n");
			return -1;
		}



		if(pthread_create(&tid1,NULL,partB,NULL)!=0)
		{
			fprintf(stderr,"pthread_create2 falled\n");
			return -1;
		}

		pthread_join(tid1,NULL);



	sem_destroy(&sem);



	return 0;
}

实现结果:

ubuntu@ubuntu:07_day$ gcc cat.c -pthread
ubuntu@ubuntu:07_day$ ./a.out
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <string.h>
#include <semaphore.h>
//临界资源
char str[10]="1234567";
sem_t sem,sem1;
void *callback(void *arg)
{
	int n=strlen(str);
	char c;

	while(1)
	{
		/*********临界区*********/
		sem_wait(&sem);
		for(int i=0;i<n/2;i++)
		{
			c=str[i];
			str[i]=str[n-1-i];
			str[n-1-i]=c;
		}
		sem_post(&sem1);

		/*********临界区*********/
	}
	
	pthread_exit(NULL);

}

void *prtf(void *arg)
{
	
	while(1)
	{
		/*********临界区*********/
		
		sem_wait(&sem1);

		printf("%s\n",str);

		sem_post(&sem);

		/*********临界区*********/
	}

	return NULL;

}

int main(int argc, const char *argv[])
{
	//创建一个分支线程
	pthread_t tid;

	pthread_t tid1;


	//创建一个信号量
	sem_init(&sem,0,1);
	sem_init(&sem1,0,1)'


	
		if(pthread_create(&tid,NULL,callback,NULL) != 0)
		{
			fprintf(stderr,"pthread_create falled\n");
			return -1;
		}

		pthread_detach(tid);


		if(pthread_create(&tid1,NULL,prtf,NULL)!=0)
		{
			fprintf(stderr,"pthread_create2 falled\n");
			return -1;
		}

		pthread_join(tid1,NULL);


	sem_destroy(&sem);



	return 0;
}
ubuntu@ubuntu:07_day$ 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值