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

相关推荐
码出财富1 天前
SpringBoot 内置的 20 个高效工具类
java·spring boot·spring cloud·java-ee
多米Domi0111 天前
0x3f第33天复习 (16;45-18:00)
数据结构·python·算法·leetcode·链表
我是小疯子661 天前
Python变量赋值陷阱:浅拷贝VS深拷贝
java·服务器·数据库
森叶1 天前
Java 比 Python 高性能的原因:重点在高并发方面
java·开发语言·python
二哈喇子!1 天前
Eclipse中导入外部jar包
java·eclipse·jar
微露清风1 天前
系统性学习C++-第二十二讲-C++11
java·c++·学习
罗湖老棍子1 天前
【例4-11】最短网络(agrinet)(信息学奥赛一本通- P1350)
算法·图论·kruskal·prim
方圆工作室1 天前
【C语言图形学】用*号绘制完美圆的三种算法详解与实现【AI】
c语言·开发语言·算法
Lips6111 天前
2026.1.16力扣刷题
数据结构·算法·leetcode
进阶小白猿1 天前
Java技术八股学习Day20
java·开发语言·学习