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;
}
相关推荐
Gofarlic_oms14 小时前
利用API实现ANSYS许可证管理自动化集成
运维·服务器·开发语言·matlab·自动化·负载均衡
AI+程序员在路上5 小时前
VS Code 完全使用指南:下载、安装、核心功能与 内置AI 编程助手实战
开发语言·人工智能·windows·开源
invicinble5 小时前
这里对java的知识体系做一个全域的介绍
java·开发语言·python
catchadmin5 小时前
使用 PHP TrueAsync 改造 Laravel 协程异步化的可行路径
开发语言·php·laravel
wbs_scy5 小时前
【Linux 线程进阶】进程 vs 线程资源划分 + 线程控制全详解
java·开发语言
ss2735 小时前
食谱推荐系统功能测试如何写?
java·数据库·spring boot·功能测试
AI人工智能+电脑小能手6 小时前
【大白话说Java面试题】【Java基础篇】第15题:JDK1.7中HashMap扩容为什么会发生死循环?如何解决
java·开发语言·数据结构·后端·面试·哈希算法
m0_674294646 小时前
如何编写SQL存储过程性能对比_记录执行时间评估优化效果
jvm·数据库·python
try2find6 小时前
打印ascii码报错问题
java·linux·前端
014-code6 小时前
CompletableFuture 实战模板(超时、组合、异常链处理)
java·数据库