使用IO进程完成图片的拷贝

题:要求用两个线程拷贝一张图片,A线程拷贝前半部分,B线程拷贝后半部分

不允许使用sleep函数,不允许使用flag。
代码如下:

 

#include<stdio.h>
#include<pthread.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
    
pthread_mutex_t mutex; 	//互斥锁
int fd;
int gf;
off_t size;

void *callbackA(void *arg)   //进程A

{	
	  pthread_detach(pthread_self());   
	 
      
      char buf2=0;
	 
	for(int i=0;i<=size/2;i++)
	{pthread_mutex_lock(&mutex); 	//上锁

		lseek(fd,size/2+i,SEEK_SET);
		lseek(gf,size/2+i,SEEK_SET);


		if(read(fd, &buf2, 1) <= 0)
		{
			perror("read");
		}

		write(gf,&buf2,1);
		pthread_mutex_unlock(&mutex);	//解锁

	}
 
      pthread_exit(NULL);
	  
}

void *callbackB(void *arg)  //进程B
{
	pthread_detach(pthread_self());
	
    
	char buf=0;

	for(int i=0;i<size/2;i++)
	{		pthread_mutex_lock(&mutex); 	//上锁

		lseek(fd,i,SEEK_SET);
		lseek(gf,i,SEEK_SET);

		if(read(fd, &buf, 1) <= 0)
		{
			perror("read");
		}
		write(gf,&buf,1);
		pthread_mutex_unlock(&mutex); 	//解锁

	}
    pthread_exit(NULL);
	
}

int main(int argc, const char *argv[])
{
     //创建互斥锁,并初始化
	if(pthread_mutex_init(&mutex, NULL) != 0)
	{
		perror("pthread_mutex_init");
		return -1;
	}

	 fd = open("./4.png",O_RDONLY);   //打开指定要复制的图片文件


	 gf = open("./5.png",O_RDWR|O_TRUNC|O_CREAT,0664); //复制的图片


	 size = lseek(fd,0,SEEK_END); //算出图片的大


	 printf("mutex_init success\n");

	 printf("准备运行程序\n");

	 pthread_t tid1,tid2;  //创建两个线程

	 if(pthread_create(&tid1,NULL,callbackA,NULL) != 0)
	 {
		 perror("pthread_create");
		 return -1;
	 }

     if(pthread_create(&tid2, NULL, callbackB,NULL) != 0)
	 {
		 perror("pthread_create");
		 return -1;
	 }

	 printf("线程创建成功\n");
	 pthread_join(tid1, NULL);
	 pthread_join(tid2, NULL);
	 close(gf);
	 close(fd);
     pthread_mutex_destroy(&mutex);



	

	 
	
	
	return 0;
}

原图:

 运行结果:

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值