IO 作业 24/2/21

1、使用多线程完成两个文件的拷贝,第一个线程拷贝前一半,第二个线程拷贝后一半,主线程回收两个线程的资源

复制代码
#include <myhead.h>
//定义分支线程1
void *task1(void *arg)
{
	int fdr=-1;
	//只读打开被复制文件
	if((fdr=open("./111.txt",O_RDONLY))==-1)
	{
		perror("open_r error");
		return NULL;
	}
	int fdw=-1;
	//只写打开目标文件文件
	if((fdw=open("./222.txt",O_WRONLY|O_CREAT,0664))==-1)
	{
		perror("open_w error");
		return NULL;
	}
	//文件字节大小
	off_t size=lseek(fdr,0,SEEK_END);
	//光标
	lseek(fdr,0,SEEK_SET);
	lseek(fdw,0,SEEK_SET);
	//定义数组读取字符
	char strR[10]="";
	int sum=0;
	while(1)
	{
		int res=read(fdr,strR,sizeof(strR));
		sum+=res;
		if(sum>=size/2||res==0)
		{
			write(fdw,strR,res-(sum-size/2));
			break;
		}
		write(fdw,strR,res);
	//	printf("111\n");
	}
	//关闭文件
	close(fdr);
	close(fdw);
	pthread_exit;
}
//定义分支线程2
void *task2(void *arg)
{
	int fdr=-1;
	//只读打开被复制文件
	if((fdr=open("./111.txt",O_RDONLY))==-1)
	{
		perror("open_r error");
		return NULL;
	}
	int fdw=-1;
	//只写打开目标文件文件
	if((fdw=open("./222.txt",O_WRONLY|O_CREAT,0664))==-1)
	{
		perror("open_w error");
		return NULL;
	}
	//文件字节大小
	off_t size=lseek(fdr,0,SEEK_END);
	//光标
	lseek(fdr,size/2,SEEK_SET);
	lseek(fdw,size/2,SEEK_SET);
	//定义数组读取字符
	char strR[10]="";
	int sum=0;
	while(1)
	{
		int res=read(fdr,strR,sizeof(strR));
		sum+=res;
		if(sum>=size/2||res==0)
		{
			write(fdw,strR,res-(sum-(size-size/2)));
			break;
		}
		write(fdw,strR,res);
	//	printf("111\n");
	}
	//关闭文件
	close(fdr);
	close(fdw);
	pthread_exit;
}
int main(int argc, const char *argv[])
{
	//定义线程号变量
	pthread_t tid1=-1;
	pthread_t tid2=-1;
	//创建线程1
	if(pthread_create(&tid1,NULL,task1,NULL)!=0)
	{
		printf("tid1 create error\n");
		return -1;
	}
	//创建线程2
	if(pthread_create(&tid2,NULL,task2,NULL)!=0)
	{
		printf("tid2 create error\n");
		return -1;
	}
	//回收线程资源
	pthread_join(tid1,NULL);
	pthread_join(tid2,NULL);
	return 0;
}

2、思维导图

相关推荐
杂货铺的小掌柜8 分钟前
apache poi excel 字体数量限制
java·excel·poi
大厂码农老A16 分钟前
你打的日志,正在拖垮你的系统:从P4小白到P7专家都是怎么打日志的?
java·前端·后端
朝新_18 分钟前
【优选算法】第一弹——双指针(上)
算法
艾菜籽32 分钟前
Spring MVC入门补充2
java·spring·mvc
艾莉丝努力练剑41 分钟前
【C++STL :stack && queue (一) 】STL:stack与queue全解析|深入使用(附高频算法题详解)
linux·开发语言·数据结构·c++·算法
爆更小哇42 分钟前
统一功能处理
java·spring boot
程序员鱼皮44 分钟前
我造了个程序员练兵场,专治技术焦虑症!
java·计算机·程序员·编程·自学
CoovallyAIHub1 小时前
ICLR 2026 惊现 SAM 3,匿名提交,实现“概念分割”,CV领域再迎颠覆性突破?
深度学习·算法·计算机视觉
IT古董1 小时前
【第五章:计算机视觉-计算机视觉在工业制造领域中的应用】1.工业缺陷分割-(2)BiseNet系列算法详解
算法·计算机视觉·制造
n8n1 小时前
SpringAI 完全指南:为Java应用注入生成式AI能力
java·后端