IO进程线程0802作业-洪庆乐

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

不允许使用sleep函数,不允许使用fla

#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>

pthread_mutex_t mutex;
int fd_rd;
int fd_cp;
off_t size;
//A线程
void* callBackA(void* arg)
{
	pthread_detach(pthread_self());

	pthread_mutex_lock(&mutex);
	lseek(fd_rd,0,SEEK_SET);
	lseek(fd_cp,0,SEEK_SET);
	int i = 0;
	char c;
	for(i=0; i<size/2; i++)
	{
		if(read(fd_rd, &c, 1) <= 0)
		{
			perror("read");
		}
		write(fd_cp, &c, 1);
	}
	pthread_mutex_unlock(&mutex);

	pthread_exit(NULL);
}


//B线程
void* callBackB(void* arg)
{
	pthread_detach(pthread_self());
	
	pthread_mutex_lock(&mutex);
	lseek(fd_rd,size/2,SEEK_SET);
	lseek(fd_cp,size/2,SEEK_SET);
	int i = 0;
	char c = 0;
	for(i=size/2; i<size; i++)
	{
		if(read(fd_rd, &c, 1) <= 0)
		{
			perror("read");
		}
		write(fd_cp, &c, 1);
	}
	pthread_mutex_unlock(&mutex);

	pthread_exit(NULL);
}

int main(int argc, const char *argv[])
{
	printf("准备运行程序\n");

	//打开原图片
	fd_rd = open("./1.png",O_RDONLY);
	if(fd_rd < 0)
	{
		perror("open");
		exit(0);
	}

	//打开要拷贝到的位置文件
	fd_cp = open("./copy.png",O_RDWR|O_TRUNC|O_CREAT,07770);
	if(fd_cp < 0)
	{
		perror("open");
		exit(0);
	}
	size = lseek(fd_rd, 0, SEEK_END);
	int i = 0;
	for(i=0; i<size; i++)
	{
		write(fd_cp, "\0", 1);
	}
	//创建锁	
	pthread_mutex_init(&mutex,NULL);

	//创建A线程
	pthread_t tida;
	if(pthread_create(&tida,NULL,callBackA,NULL) != 0)
	{
		perror("pthread_create");
		return -1;
	}

	//创建B线程
	pthread_t tidb;
	if(pthread_create(&tidb,NULL,callBackB,NULL) != 0)
	{
		perror("pthread_create");
		return -1;
	}

	pthread_join(tida,NULL);
	pthread_join(tidb,NULL);


	close(fd_rd);
	close(fd_cp);
	//销毁锁
	pthread_mutex_destroy(&mutex);

	return 0;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值