作业12.12----用两个线程拷贝一张图片,要求A线程拷贝前半部分,B线程拷贝后半部分;提示:找到临界资源,临界区,上锁解锁即可;

 

用两个线程拷贝一张图片,要求A线程拷贝前半部分,B线程拷贝后半部分;提示:找到临界资源,临界区,上锁解锁即可;

#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
//结构体定义,需要传入到分支线程的数据类型结构体
struct info
{
	int fd_r;
	int fd_w;
	off_t size;
};

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

void* thread_func1(void* arg)
{

	int fd_r=((struct info*)arg)->fd_r;
	int fd_w=((struct info*)arg)->fd_w;
	off_t size=((struct info*)arg)->size;
	pthread_mutex_lock(&mutex);

	/*      临界区       */
	//修改文件偏移量到0的位置
	lseek(fd_r,0,SEEK_SET);
	lseek(fd_w,0,SEEK_SET);
	char c = 0;
	//循环写入
	for(int i=0;i<size/2;i++)
	{   
		if(read(fd_r,&c,1)<0)
		{
			perror("read");
			return 0;
		}
		if(write(fd_w,&c,1)<0)
		{
			perror("write");
			return 0;
		}
	}
	
	pthread_mutex_unlock(&mutex);
	/*      临界区       */
	printf("前半部分拷贝完成\n");
	pthread_exit(NULL);
}
void *thread_func2(void *arg)
{

	int fd_r=((struct info*)arg)->fd_r;
	int fd_w=((struct info*)arg)->fd_w;
	off_t size=((struct info*)arg)->size;
	char flag = size%2==1?1:0;
	/*      临界区       */
	pthread_mutex_lock(&mutex);
	//修改文件偏移量到size/2的位置
	lseek(fd_r,size/2,SEEK_SET);
	lseek(fd_w,size/2,SEEK_SET);
	char c = 0;
	//循环写入
	for(int i=0;i<size/2+flag;i++)
	{
    	if(read(fd_r,&c,1)<0)
		{
			perror("read");
			return 0;
		}
		if(write(fd_w,&c,1)<0)
		{
			perror("write");
			return 0;
		}
	}
	pthread_mutex_unlock(&mutex);
	/*      临界区       */
    printf("后半部分拷贝完成\n");
	pthread_exit(NULL);
}

int main(int argc, const char *argv[])
{  
	//打开两个文件
	//以读的方式打开文件
	int fd_r=open("./1.png",O_RDONLY);
	if(fd_r<0)
	{
        perror("open");
		return -1;
	}
	//以写的方式打开文件
	int fd_w=open("./2.png",O_WRONLY|O_CREAT|O_TRUNC,0664);
	if(fd_w<0)
	{
		perror("open");
		return -1;
	}
	//接收文件大小
	off_t size = lseek(fd_r,0,SEEK_END);
	//需要传入到线程中的数据
	struct info msg;
	msg.fd_r=fd_r;
	msg.fd_w=fd_w;
	msg.size=size;
	//pthread_mutex_init(&mutex,NULL);
	pthread_t tid1;
	if(pthread_create(&tid1,NULL,thread_func1,&msg)!=0)
	{
		printf("分支线程1创建失败\n");
		return -1;
	}
	pthread_t tid2;
	if(pthread_create(&tid2,NULL,thread_func2,&msg)!=0)
	{
		printf("分支线程2创建失败\n");
		return -1;
	}

	pthread_join(tid1,NULL);
	pthread_join(tid2,NULL);

	close(fd_r);
	close(fd_w);
	//销毁互斥锁
	pthread_mutex_destroy(&mutex);
	return 0;
}

代码执行结果

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值