需求:
利用线程与互斥锁拷贝图片,线程A拷贝前半部分,线程B拷贝后半部分
代码实现过程:
#include<stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <pthread.h>
#include <stdlib.h>
#include <string.h>
pthread_mutex_t mutex;
char str[32]="";
int res = 0;
struct info{
int fd1;
int fd2;
off_t size;
};
void *funcA(void *arg){
int fd1 = ((struct info*)arg)->fd1;
int fd2 = ((struct info*)arg)->fd2;
off_t size = ((struct info*)arg)->size;
ssize_t half_size = size/2;
ssize_t read_size = 0;
ssize_t offset = 0;
while(1){
//locking
pthread_mutex_lock(&mutex);
lseek(fd1,offset,SEEK_SET);
lseek(fd2,offset,SEEK_SET);
read_size = half_size/sizeof(str)==0?half_size:sizeof(str);
res = read(fd1,str,read_size);
if(res == 0){
pthread_mutex_unlock(&mutex);
break;
}
if(write(fd2,str,res)<0){
perror("write");
return NULL;
}
if((half_size -= read_size) < 0){
printf("0\n");
break;
}
offset = lseek(fd1,0,SEEK_CUR);
pthread_mutex_unlock(&mutex);
//unlocking
}
pthread_exit(NULL);
return NULL;
}
void *funcB(void *arg){
int fd1 = ((struct info*)arg)->fd1;
int fd2 = ((struct info*)arg)->fd2;
off_t size = ((struct info*)arg)->size;
ssize_t offset = size/2;
while(1){
//locking
pthread_mutex_lock(&mutex);
lseek(fd1,offset,SEEK_SET);
lseek(fd2,offset,SEEK_SET);
res = read(fd1,str,sizeof(str));
if(res == 0){
pthread_mutex_unlock(&mutex);
break;
}
if(write(fd2,str,res) < 0){
perror("write");
return NULL;
}
offset = lseek(fd1,0,SEEK_CUR);
pthread_mutex_unlock(&mutex);
//unlocking
}
pthread_exit(NULL);
return NULL;
}
int main(int argc, const char *argv[])
{
int fd1 = open("./1.png",O_RDONLY);
int fd2= open("./copy.png",O_RDWR|O_CREAT,0664);
if(fd1 < 0 || fd2 < 0){
perror("open");
return -1;
}
struct info msg;
msg.fd1 = fd1;
msg.fd2 = fd2;
off_t size = lseek(fd1,0,SEEK_END);
msg.size = size;
pthread_mutex_init(&mutex,NULL);
pthread_t tidA;
if(pthread_create(&tidA,NULL,funcA,&msg) != 0){
fprintf(stderr,"pthread_create A\n");
return -1;
}
pthread_t tidB;
if(pthread_create(&tidB,NULL,funcB,&msg) != 0){
fprintf(stderr,"pthread_create B\n");
return -1;
}
if(pthread_join(tidB,NULL) != 0 || pthread_join(tidA,NULL) != 0){
fprintf(stderr,"pthread_join\n");
return -1;
}
if(pthread_mutex_destroy(&mutex) != 0){
fprintf(stderr,"pthread_mutex_destroy\n");
return -1;
}
if(close(fd1) < 0 || close(fd2) < 0){
perror("close");
return -1;
}
return 0;
}
代码实现结果: