IO进程线程day5

作业

使用两个线程完成两个文件的拷贝,分支线程1完成前一半内容拷贝,分支线程2完成后一半内容的拷贝,主线程完成资源的回收

cpp 复制代码
#include<myhead.h>
//全局定义一个互斥锁变量
pthread_mutex_t first_mutex;

typedef  struct xxx
{
	//源文件fd
	int srcfd;
	//目标文件fd
	int destfd;

}info;

void *copy_pthread(void *buf);
int main(int argc, const char *argv[])
{

	if(argc!=3)
	{
		printf("error!!!,please check");
		return -1;
	}
	pid_t srcfd=-1;
	pid_t destfd=-1;
	//只读形式打开源文件
	if((srcfd=open(argv[1],O_RDONLY))==-1)
	{
		perror("open srcfd error");	
		return -1;
	}
	//追加读写形式打开目标文件,不存在的话创建
	if((destfd=open(argv[2],O_RDWR|O_CREAT|O_APPEND,0664))==-1)
	{
		perror("open srcfd error");	
		return -1;
	}
	//结构体初始化
	info buf={srcfd,destfd};

	//初始化互斥锁
	pthread_mutex_init(&first_mutex,NULL);

	pthread_t tid1=-1;
	pthread_t tid2=-1;
	//1线程创建函数成功会返回0
	if(pthread_create(&tid1,NULL,copy_pthread,&buf)!=0)
	{
		printf("1create fail");
		return -1;
	}
	//2线程创建函数成功会返回0
	if(pthread_create(&tid2,NULL,copy_pthread,&buf)!=0)
	{
		printf("2create fail");
		return -1;
	}





	//回收分支线程
	pthread_join(tid1,NULL);
	pthread_join(tid2,NULL);

	//关闭文件
	close(srcfd);
	close(destfd);
	puts("guanbi");
	//销毁互斥锁;
	pthread_mutex_destroy(&first_mutex);

	return 0;
}
void *copy_pthread(void *buf)
{
	info arg=*(info *)buf;

	//临界区上锁:获取锁资源
	pthread_mutex_lock(&first_mutex);

	int length=lseek(arg.srcfd,0,SEEK_END);
	char xxx[length/2]="2312";
	printf("%ld\n",sizeof(xxx));
	int ret=read(arg.srcfd,xxx,sizeof(xxx));
	printf("%s\n",xxx);
	write(arg.destfd,xxx,5);


	sleep(2);

	//临界区开锁:释放锁资源
	pthread_mutex_unlock(&first_mutex);
	return NULL;
}
相关推荐
songgz6 小时前
双向流式 JSON 解析架构:并行优化大型文件处理
java·开发语言·json
adfass6 小时前
桌面挂件时钟/多功能时钟C++
开发语言·c++·算法
Rust语言中文社区7 小时前
【Rust日报】 walrus:分布式消息流平台,比 Kafka 快
开发语言·分布式·后端·rust·kafka
6***09267 小时前
Spring 中集成Hibernate
java·spring·hibernate
z***02607 小时前
Spring Boot管理用户数据
java·spring boot·后端
多多*7 小时前
Threadlocal深度解析 为什么key是弱引用 value是强引用
java·开发语言·网络·jvm·网络协议·tcp/ip·mybatis
Python×CATIA工业智造7 小时前
Python多进程爬虫实战:豆瓣读书数据采集与法律合规指南
开发语言·爬虫·python
z***39627 小时前
Plugin ‘org.springframework.bootspring-boot-maven-plugin‘ not found(已解决)
java·前端·maven
星尘库7 小时前
.NET Framework中报错命名空间System.Text中不存在类型或命名空间名Json
java·json·.net
百***35487 小时前
后端在微服务中的Docker
java·docker·微服务