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

相关推荐
工业互联网专业12 分钟前
基于springboot+vue的病例管理系统
java·vue.js·spring boot·毕业设计·源码·课程设计·病例管理系统
2301_7944615713 分钟前
力扣-快乐数
算法·leetcode·职场和发展
chenyuhao202422 分钟前
链表面试题9之环形链表进阶
数据结构·算法·链表·面试·c#
chenyuhao20241 小时前
链表的面试题8之环形链表
数据结构·算法·链表·面试·c#
Yan_ks1 小时前
JAVA面向对象——对象和类的基本语法
java·开发语言
Panesle1 小时前
Index-AniSora模型论文速读:基于人工反馈的动漫视频生成
人工智能·算法·机器学习·计算机视觉·开源·大模型·生成模型
Paddy哥1 小时前
jsmpeg+java+ffmpeg 调用摄像头RTSP流播放
java·开发语言·ffmpeg
liuzhangfeiabc2 小时前
[luogu12542] [APIO2025] 排列游戏 - 交互 - 博弈 - 分类讨论 - 构造
c++·算法·题解
oioihoii2 小时前
C++23 新增扁平化关联容器详解
java·开发语言·c++23
晴空闲雲2 小时前
数据结构与算法-线性表-循环链表(Circular Linked List)
数据结构·算法·链表