作业cccc

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

#include<stdio.h>
#include<pthread.h>
#include<string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
pthread_mutex_t mutex; 	
int fd_r; 
int fd_w;
off_t size;
int flag;
void* fun1(void* arg)
{
	int i;
	char c;
	off_t offset=0;

	for(i=0;i<size/2;i++)
	{
		pthread_mutex_lock(&mutex);
		lseek(fd_r,offset,SEEK_SET);
		lseek(fd_w,offset,SEEK_SET);

		read(fd_r,&c,1);
		write(fd_w,&c,1);
		offset=lseek(fd_r,0,SEEK_CUR);
		pthread_mutex_unlock(&mutex);
	}
	printf("前面一半拷贝成功\n");
	pthread_exit(NULL);

}
void* fun2(void* arg)
{	
	flag=size%2==0?0:1;

	int i=0;
	char c;
	off_t offset=size/2;
	for(i=0;i<size/2+flag;i++)
	{
		pthread_mutex_lock(&mutex);
		lseek(fd_r,offset,SEEK_SET);
		lseek(fd_w,offset,SEEK_SET);
		read(fd_r,&c,1);
		write(fd_w,&c,1);
		offset=lseek(fd_r,0,SEEK_CUR);
		pthread_mutex_unlock(&mutex);

	}
	printf("后一半拷贝成功\n");

	pthread_exit(NULL);

}

int main(int argc, const char *argv[])
{
	//以读的方式打开源文件
	fd_r = open("1.png", O_RDONLY);
	if(fd_r < 0)
	{
		perror("open");
		//return -1;
	}

	//以写的方式打开目标文件
	fd_w = open("2.png", O_WRONLY|O_CREAT|O_TRUNC, 0664);
	if(fd_w < 0)
	{
		perror("open");
		return -1;
	}

	//计算文件大小
	size = lseek(fd_r, 0, SEEK_END);
	printf("size = %ld \n", size);

	//创建互斥锁,并初始化
	if(pthread_mutex_init(&mutex, NULL) != 0)
	{
		perror("pthread_mutex_init");
		return -1;
	}
	printf("mutex_init success\n");

	//创建一个线程,拷贝一半
	pthread_t tid_a;
	if (pthread_create(&tid_a,NULL,fun1,NULL)!=0)
	{
		perror("thread_create_a");
		return -1;
	}

	//创建一个线程,拷贝另一半
	pthread_t tid_b;
	if (pthread_create(&tid_b,NULL,fun2,NULL)!=0)
	{
		perror("thread_create_b");
		return -1;
	}

	printf("线程创建成功\n");

	pthread_join(tid_a, NULL);
	pthread_join(tid_b, NULL);

	//销毁互斥锁
	pthread_mutex_destroy(&mutex);	

	//关闭文件
	close(fd_r);
	close(fd_w);
	return 0;
}

结果

 

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值