![在这里插入图片描述](https://img-blog.csdnimg.cn/direct/a3d588d3e5e4457281ca2192c85e4313.png#pic_cente
#include <stdio.h>
#include<pthread.h>
#include<unistd.h>
#include<string.h>
#include<stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
//打开文件
void* aa(void*a){
char cc;
int fd=open("./1.png",O_RDONLY);
if(fd<0){
perror("open");
return NULL;
}
struct stat buf;
if(stat("./1.png",&buf)<0){
perror("stat");
return NULL;
}
int fd1=open("./cp.png",O_WRONLY|O_CREAT,0777);
if(fd1<0){
perror("open");
return NULL;
}
lseek(fd,buf.st_size/2,SEEK_SET);
lseek(fd1,buf.st_size/2,SEEK_SET);
pthread_mutex_lock((pthread_mutex_t*)a);
for(int i=0;i<buf.st_size/2;i++){
read(fd,&cc,1);
write(fd1,&cc,1);
}
printf("完成1");
pthread_mutex_unlock((pthread_mutex_t*)a);
//return;
}
void*bb(void*a){
char cc;
int fd=open("./1.png",O_RDONLY);
if(fd<0){
perror("open");
return NULL;
}
struct stat buf;
if(stat("./1.png",&buf)<0){
perror("stat");
return NULL;
}
int fd1=open("./cp.png",O_WRONLY|O_CREAT|O_TRUNC,0777);
if(fd1<0){
perror("open");
return NULL;
}
lseek(fd,0,SEEK_SET);
lseek(fd1,0,SEEK_SET);
pthread_mutex_lock((pthread_mutex_t*)a);
for(int i=0;i<buf.st_size/2;i++){
read(fd,&cc,1);
write(fd1,&cc,1);
}
printf("完成2");
pthread_mutex_unlock((pthread_mutex_t*)a);
}
int main(int argc, const char *argv[])
{
pthread_mutex_t mutex;
pthread_mutex_init(&mutex,NULL);
pthread_t tid1,tid2;
if(pthread_create(&tid1,NULL,aa,(void*)&mutex)!=0){
return -1;
}
if(pthread_create(&tid2,NULL,bb,(void*)&mutex)!=0){
return -1;
}
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
pthread_mutex_destroy(&mutex);
return 0;
}