8 月 3日 IO DAY 6

本文描述了如何使用C语言和POSIX线程库创建两个并发线程,一个负责文件的前半部分拷贝,另一个负责后半部分,通过互斥锁保证临界区操作的正确执行。
摘要由CSDN通过智能技术生成

作业

创建两个线程:其中一个线程拷贝前半部分,另一个线程拷贝后半部分。

只允许开一份资源,且用互斥锁方式实现。 提示:找临界区---》找临界资源。

代码

#include <stdio.h>
#include <head.h>

struct Msg
{
	int fd_r;
	int fd_w;
	off_t size;
};

pthread_mutex_t mutex;


void *callBack1(void *arg)
{
	
	int fd_r = ((struct Msg*)arg) -> fd_r;
	int fd_w = ((struct Msg*)arg) -> fd_w;
	off_t size = ((struct Msg*)arg) -> size;

	

	char c = 0;
	pthread_mutex_lock(&mutex);

	lseek(fd_r, 0, SEEK_SET);
	lseek(fd_w, 0, SEEK_SET);

	for (int i = 0; i < size / 2; i++)
	{
		read(fd_r, &c, 1);
		write(fd_w, &c, 1);
	}
	printf("上半部分拷贝完毕\n");
	pthread_mutex_unlock(&mutex);
	
	printf("线程1准备退出\n");
	pthread_exit(NULL);
	return NULL;
}

void *callBack2(void *arg)
{
	 

	int fd_r = ((struct Msg*)arg) -> fd_r;
	int fd_w = ((struct Msg*)arg) -> fd_w;
	off_t size = ((struct Msg*)arg) -> size;

	

	char c = 0;
	pthread_mutex_lock(&mutex);

	lseek(fd_r, size / 2, SEEK_SET);
	lseek(fd_w, size / 2, SEEK_SET);

	for (int i = size / 2; i < size; i++)
	{
		read(fd_r, &c, 1);
		write(fd_w, &c, 1);
	}
	printf("下半部分拷贝完毕\n");
	pthread_mutex_unlock(&mutex);

	printf("线程2准备退出\n");
	
	pthread_exit(NULL);
	return NULL;
}

int main(int argc, const char *argv[])
{
	pthread_mutex_init(&mutex, NULL);

	printf("<---若出现拷贝完毕提示,可以按回车结束该程序--->\n");
	//pthread_mutex_lock(&mutex);
	int fd_r = open("./1.png", O_RDONLY);
	if (fd_r < 0)
	{
		ERR_MSG("open");
		return -1;
	}
	
	int fd_w = open("copy1.png", O_WRONLY | O_CREAT | O_TRUNC, 0664);
	if (fd_w < 0)
	{
		ERR_MSG("open");
		return -1;
	}
	off_t size = lseek(fd_r, 0, SEEK_END);
	struct Msg filemsg = {fd_r, fd_w, size};

	pthread_t tid1, tid2;
	if (pthread_create(&tid1, NULL, callBack1, &filemsg) != 0)
	{
		fprintf(stderr, "pthread_create fail __%d__\n", __LINE__);
		return -1;
	}
	//pthread_mutex_unlock(&mutex);
	
	
	if (pthread_create(&tid2, NULL, callBack2, &filemsg) != 0)
	{
		fprintf(stderr, "pthread_create fail __%d__\n", __LINE__);
		return -1;
	}

	//pthread_detach(tid2);
	

	// pthread_join(tid1, NULL);
	// pthread_join(tid2, NULL);
	//pthread_mutex_lock(&mutex);


	//pthread_detach(tid1);

	//pthread_mutex_unlock(&mutex);

	//pthread_mutex_lock(&mutex);


	//pthread_detach(tid2);

	//pthread_mutex_unlock(&mutex);
	char s;
	s = getchar();
	pthread_mutex_destroy(&mutex);
	close(fd_r);
	close(fd_w);
	printf("文件拷贝完毕\n");

	
	return 0;
}




截图

思维导图

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值