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;
}
相关推荐
丶白泽6 分钟前
重修设计模式-结构型-桥接模式
java·设计模式·桥接模式
o独酌o12 分钟前
递归的‘浅’理解
java·开发语言
Book_熬夜!15 分钟前
Python基础(六)——PyEcharts数据可视化初级版
开发语言·python·信息可视化·echarts·数据可视化
无问81724 分钟前
数据结构-排序(冒泡,选择,插入,希尔,快排,归并,堆排)
java·数据结构·排序算法
m0_6312704042 分钟前
高级c语言(五)
c语言·开发语言
customer081 小时前
【开源免费】基于SpringBoot+Vue.JS在线文档管理系统(JAVA毕业设计)
java·vue.js·spring boot·后端·开源
2401_858286111 小时前
53.【C语言】 字符函数和字符串函数(strcmp函数)
c语言·开发语言
Flying_Fish_roe1 小时前
Spring Boot-版本兼容性问题
java·spring boot·后端
程序猿进阶1 小时前
如何在 Visual Studio Code 中反编译具有正确行号的 Java 类?
java·ide·vscode·算法·面试·职场和发展·架构
程序猿练习生1 小时前
C++速通LeetCode中等第5题-无重复字符的最长字串
开发语言·c++·leetcode