要求用两个线程拷贝一张图片,A线程拷贝前半部分,B线程拷贝后半部分
不允许使用sleep函数,不允许使用fla
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
pthread_mutex_t mutex;
int fd_rd;
int fd_cp;
off_t size;
//A线程
void* callBackA(void* arg)
{
pthread_detach(pthread_self());
pthread_mutex_lock(&mutex);
lseek(fd_rd,0,SEEK_SET);
lseek(fd_cp,0,SEEK_SET);
int i = 0;
char c;
for(i=0; i<size/2; i++)
{
if(read(fd_rd, &c, 1) <= 0)
{
perror("read");
}
write(fd_cp, &c, 1);
}
pthread_mutex_unlock(&mutex);
pthread_exit(NULL);
}
//B线程
void* callBackB(void* arg)
{
pthread_detach(pthread_self());
pthread_mutex_lock(&mutex);
lseek(fd_rd,size/2,SEEK_SET);
lseek(fd_cp,size/2,SEEK_SET);
int i = 0;
char c = 0;
for(i=size/2; i<size; i++)
{
if(read(fd_rd, &c, 1) <= 0)
{
perror("read");
}
write(fd_cp, &c, 1);
}
pthread_mutex_unlock(&mutex);
pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
printf("准备运行程序\n");
//打开原图片
fd_rd = open("./1.png",O_RDONLY);
if(fd_rd < 0)
{
perror("open");
exit(0);
}
//打开要拷贝到的位置文件
fd_cp = open("./copy.png",O_RDWR|O_TRUNC|O_CREAT,07770);
if(fd_cp < 0)
{
perror("open");
exit(0);
}
size = lseek(fd_rd, 0, SEEK_END);
int i = 0;
for(i=0; i<size; i++)
{
write(fd_cp, "\0", 1);
}
//创建锁
pthread_mutex_init(&mutex,NULL);
//创建A线程
pthread_t tida;
if(pthread_create(&tida,NULL,callBackA,NULL) != 0)
{
perror("pthread_create");
return -1;
}
//创建B线程
pthread_t tidb;
if(pthread_create(&tidb,NULL,callBackB,NULL) != 0)
{
perror("pthread_create");
return -1;
}
pthread_join(tida,NULL);
pthread_join(tidb,NULL);
close(fd_rd);
close(fd_cp);
//销毁锁
pthread_mutex_destroy(&mutex);
return 0;
}