代码实现如下:
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
//结构体定义,需要传入到分支线程的数据类型结构体
struct info
{
int fd_r;
int fd_w;
off_t size;
};
//互斥锁的初始化
pthread_mutex_t mutex;
void *funcA(void *arg) //void *arg == &msg;
{
int fd_r = ((struct info*)arg)->fd_r;
int fd_w = ((struct info*)arg)->fd_w;
off_t size = ((struct info*)arg)->size;
off_t offset = 0; //记录当前对文件修改后的偏移量
char buf[10] = {0};
ssize_t res = 0;
ssize_t read_size = 0;
ssize_t half_size = size/2;
while(1)
{
/***********临界区************/
pthread_mutex_lock(&mutex);
read_size = half_size/sizeof(buf) == 0? half_size:sizeof(buf);
lseek(fd_r, offset, SEEK_SET);
lseek(fd_w, offset, SEEK_SET);
res = read(fd_r, buf, read_size);
write(fd_w, buf, res);
offset = lseek(fd_r, 0, SEEK_CUR); //记录当前位置后再解锁
pthread_mutex_unlock(&mutex);
/***********临界区************/
if((half_size-=read_size) == 0)
break;
}
printf("前半部分拷贝完毕\n");
pthread_exit(NULL);
}
void *funcB(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;
off_t offset = size/2; //记录当前对文件修改后的偏移量
char c = 0;
for(int 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);
}
int main(int argc, const char *argv[])
{
//创建互斥锁
pthread_mutex_init(&mutex, NULL);
//打开文件
int fd_r = open("./1.png",O_RDONLY);
if(fd_r < 0)
{
fprintf(stderr,"__%d__",__LINE__);
perror("open");
return -1;
}
int fd_w = open("./copy.png",O_WRONLY|O_CREAT|O_TRUNC, 0664);
if(fd_w < 0)
{
fprintf(stderr,"__%d__",__LINE__);
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_t tid;
if(pthread_create(&tid, NULL, funcA, &msg) != 0)
{
fprintf(stderr,"pthread_create failed\n");
return -1;
}
//创建一个线程拷贝下半部分
pthread_t tid2;
if(pthread_create(&tid2, NULL, funcB, &msg) != 0)
{
fprintf(stderr,"pthread_create failed\n");
return -1;
}
pthread_join(tid,NULL);
pthread_join(tid2,NULL);
//销毁互斥锁
pthread_mutex_destroy(&mutex);
//关闭文件
close(fd_r);
close(fd_w);
return 0;
}
运行结果如下:
ubuntu@ubuntu:06_2022-12-12$ gcc copy.c -pthread
ubuntu@ubuntu:06_2022-12-12$ ./a.out前半部分拷贝完毕
后半部分拷贝完毕
ubuntu@ubuntu:06_2022-12-12$
ubuntu@ubuntu:06_2022-12-12$ diff 1.png copy.png
ubuntu@ubuntu:06_2022-12-12$