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;
}
相关推荐
董先生_ad986ad2 小时前
C# 中的 `lock` 关键字本质
开发语言·c#
Lxinccode2 小时前
Java查询数据库表信息导出Word-获取数据库实现[1]:KingbaseES
java·数据库·word·获取数据库信息·获取kingbasees信息
元亓亓亓2 小时前
Java后端开发day36--源码解析:HashMap
java·开发语言·数据结构
sd21315122 小时前
RabbitMQ 复习总结
java·rabbitmq
道剑剑非道2 小时前
QT 打包安装程序【windeployqt.exe】报错c000007d原因:Conda巨坑
开发语言·qt·conda
小邓儿◑.◑3 小时前
C++武功秘籍 | 入门知识点
开发语言·c++
码银5 小时前
Java 集合:泛型、Set 集合及其实现类详解
java·开发语言
大G哥5 小时前
PHP标签+注释+html混写+变量
android·开发语言·前端·html·php
东阳马生架构5 小时前
Nacos简介—4.Nacos架构和原理
java
傻啦嘿哟5 小时前
HTTP代理基础:网络新手的入门指南
开发语言·php