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;
}
相关推荐
树码小子11 小时前
Java网络初识(4):网络数据通信的基本流程 -- 封装
java·网络
稻草人想看远方11 小时前
GC垃圾回收
java·开发语言·jvm
胡萝卜的兔11 小时前
go 日志的分装和使用 Zap + lumberjack
开发语言·后端·golang
浪扼飞舟11 小时前
c#基础(一)
开发语言·c#
en-route12 小时前
如何在 Spring Boot 中指定不同的配置文件?
java·spring boot·后端
百锦再12 小时前
在 CentOS 系统上实现定时执行 Python 邮件发送任务
java·linux·开发语言·人工智能·python·centos·pygame
echoyu.12 小时前
消息队列-kafka完结
java·分布式·kafka
七夜zippoe12 小时前
分布式事务性能优化:从故障现场到方案落地的实战手记(二)
java·分布式·性能优化
栀椩12 小时前
springboot配置请求日志
java·spring boot·后端
番薯大佬12 小时前
Python学习-day8 元组tuple
java·python·学习