Day-6练习只允许开一份资源,且用互斥锁方式实现。提示:找临界区--->找临界资源。创建两个线程:其中一个线程拷贝前半部分,另一个线程拷贝后半部分。

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

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

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <head.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
pthread_mutex_t mutex;
struct file
{
	int fd_r;
	int fd_w;
	off_t size;
};
void *callback_A(void *arg)    //void *arg = &fp
{
	int fd_r = ((struct file*)arg)->fd_r;
    int fd_w = ((struct file*)arg)->fd_w;
    off_t size = ((struct file*)arg)->size;
	//上锁
    pthread_mutex_lock(&mutex);
	lseek(fd_r, 0, SEEK_SET);
	lseek(fd_w, 0, SEEK_SET);
	char c = 0;

	for(int i=0; i<size/2; i++)
	{
		read(fd_r, &c, 1);
		write(fd_w, &c, 1);
	}

	printf("前半部分拷贝完毕\n");
	//解锁
	pthread_mutex_unlock(&mutex);
	pthread_exit(NULL);
}
void *callback_B(void *arg)    //void *arg = &fp
{
    
	
	int fd_r = ((struct file*)arg)->fd_r;
    int fd_w = ((struct file*)arg)->fd_w;
    off_t size = ((struct file*)arg)->size;
	//上锁
    pthread_mutex_lock(&mutex);
	lseek(fd_r, size/2, SEEK_SET);
	lseek(fd_w, size/2, SEEK_SET);
	char c = 0;
	for(int i=size/2; i<size; i++)
	{
		read(fd_r, &c, 1);
		write(fd_w, &c, 1);
	}
	printf("后半部分拷贝完毕\n");
	//解锁
	pthread_mutex_unlock(&mutex);
	pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{

	//申请一个互斥锁
	pthread_mutex_init(&mutex,NULL);
	
	
	//两个线程在拷贝前,确保文件存在,且是清空状态
	int fd_w = open("copy.png", O_WRONLY|O_CREAT|O_TRUNC, 0644);
	if(fd_w < 0)
	{
		ERR_MSG("open");
		return -1;
	}
    
	//以读的方式打开源文件
	int fd_r = open("666.png", O_RDONLY);
	if(fd_r < 0)
	{
		ERR_MSG("open");
		return -1;
	}
	off_t size = lseek(fd_r, 0, SEEK_END);
	struct file fp;
	fp.fd_r = fd_r;
	fp.fd_w = fd_w;
	fp.size = size;

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

	//创建一个A线程
	if(pthread_create(&tid1,NULL,callback_A,(void *)&fp) != 0)
	{
		fprintf(stderr,"pthread_create failed __%d__",__LINE__);
		return -1;
	}
	//创建一个B线程
	if(pthread_create(&tid2,NULL,callback_B,(void *)&fp) != 0)
	{
		fprintf(stderr,"pthread_create failed __%d__",__LINE__);
		return -1;
	}
    //阻塞等待分支线程退出
	pthread_join(tid1,NULL);
	pthread_join(tid2,NULL);
	
	//销毁互斥锁
	pthread_mutex_destroy(&mutex);

	close(fd_r);
	close(fd_w);
	return 0;
}

 结果为:

 

 

线程整理O_ck钉钉钉的博客-CSDN博客

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ck钉钉钉

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值