要求用两个线程拷贝一张图片,一个线程拷贝后半部分,另外一个线程拷贝前半部分。要求用文件 IO实现。 不允许使用sleep函数
#include <stdio.h>
#include <pthread.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
//需要传入到线程执行体的参数
struct msg{
int fd_r;
int fd_w;
off_t size;
};
//互斥锁
pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;
//拷贝前部分
void *callback_front(void *arg){
struct msg info=*(struct msg*)arg;
int fd_r=info.fd_r;
int fd_w=info.fd_w;
off_t size=info.size;
/*********临界区**********/
pthread_mutex_lock(&mutex);//上锁
//先将文件偏移量修改到开头
lseek(fd_r,0,SEEK_SET);
lseek(fd_w,0,SEEK_SET);
int i=0;
char c=0;
for(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_end(void *arg){
struct msg info=*(struct msg*)arg;
int fd_r=info.fd_r;
int fd_w=info.fd_w;
off_t size=info.size;
/*********临界区**********/
pthread_mutex_lock(&mutex);//上锁
//先将文件偏移量修改到中间
lseek(fd_r,size/2,SEEK_SET);
lseek(fd_w,size/2,SEEK_SET);
int i=0;
char c=0;
for(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[])
{
//创建并初始化互斥锁
if(pthread_mutex_init(&mutex,NULL)!=0){
perror("pthread_mutex_init");
return -1;
}
//以读的方式打开源文件
int fd_r=open("./hcc.png",O_RDONLY);
if(fd_r<0){
perror("open");
return -1;
}
//以写的方式打开目标文件
int fd_w=open("./HCC.png",O_WRONLY|O_CREAT|O_TRUNC,0777);
if(fd_w<0){
perror("open");
return -1;
}
//求源文件长度
off_t size=lseek(fd_r,0,SEEK_END);
lseek(fd_r,0,SEEK_SET);
struct msg info;
info.fd_r=fd_r;
info.fd_w=fd_w;
info.size=size;
pthread_t tid_front,tid_end;
//创建线程拷贝前部分
if(pthread_create(&tid_front,NULL,callback_front,(void *)&info)!=0){
perror("pthread_create");
return -1;
}
//创建线程拷贝后半部分
if(pthread_create(&tid_end,NULL,callback_end,(void *)&info)!=0){
perror("pthread_create");
return -1;
}
//主线程阻塞等待分支线程退出
pthread_join(tid_front,NULL);
pthread_join(tid_end,NULL);
//销毁互斥锁
pthread_mutex_destroy(&mutex);
close(fd_r);
close(fd_w);
return 0;
}