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、思维导图

相关推荐
武昌库里写JAVA40 分钟前
39.剖析无处不在的数据结构
java·vue.js·spring boot·课程设计·宠物管理
Nelson_hehe3 小时前
Java基础第四章、面向对象
java·语法基础·面向对象程序设计
Thomas_YXQ3 小时前
Unity3D Lua集成技术指南
java·开发语言·驱动开发·junit·全文检索·lua·unity3d
ShiinaMashirol4 小时前
代码随想录打卡|Day27(合并区间、单调递增的数字、监控二叉树)
java·算法
东阳马生架构6 小时前
Nacos简介—3.Nacos的配置简介
java
北极的企鹅886 小时前
XML内容解析成实体类
xml·java·开发语言
oioihoii6 小时前
C++23 中 static_assert 和 if constexpr 的窄化布尔转换
java·jvm·c++23
聂 可 以6 小时前
调整IntelliJ IDEA当前文件所在目录(包路径)的显示位置
java·ide·intellij-idea
wuqingshun3141596 小时前
蓝桥杯 5. 交换瓶子
数据结构·c++·算法·职场和发展·蓝桥杯
东阳马生架构6 小时前
Sentinel源码—7.参数限流和注解的实现一
java·sentinel