题:要求用两个线程拷贝一张图片,A线程拷贝前半部分,B线程拷贝后半部分
不允许使用sleep函数,不允许使用flag。
代码如下:
#include<stdio.h>
#include<pthread.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
pthread_mutex_t mutex; //互斥锁
int fd;
int gf;
off_t size;
void *callbackA(void *arg) //进程A
{
pthread_detach(pthread_self());
char buf2=0;
for(int i=0;i<=size/2;i++)
{pthread_mutex_lock(&mutex); //上锁
lseek(fd,size/2+i,SEEK_SET);
lseek(gf,size/2+i,SEEK_SET);
if(read(fd, &buf2, 1) <= 0)
{
perror("read");
}
write(gf,&buf2,1);
pthread_mutex_unlock(&mutex); //解锁
}
pthread_exit(NULL);
}
void *callbackB(void *arg) //进程B
{
pthread_detach(pthread_self());
char buf=0;
for(int i=0;i<size/2;i++)
{ pthread_mutex_lock(&mutex); //上锁
lseek(fd,i,SEEK_SET);
lseek(gf,i,SEEK_SET);
if(read(fd, &buf, 1) <= 0)
{
perror("read");
}
write(gf,&buf,1);
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;
}
fd = open("./4.png",O_RDONLY); //打开指定要复制的图片文件
gf = open("./5.png",O_RDWR|O_TRUNC|O_CREAT,0664); //复制的图片
size = lseek(fd,0,SEEK_END); //算出图片的大
printf("mutex_init success\n");
printf("准备运行程序\n");
pthread_t tid1,tid2; //创建两个线程
if(pthread_create(&tid1,NULL,callbackA,NULL) != 0)
{
perror("pthread_create");
return -1;
}
if(pthread_create(&tid2, NULL, callbackB,NULL) != 0)
{
perror("pthread_create");
return -1;
}
printf("线程创建成功\n");
pthread_join(tid1, NULL);
pthread_join(tid2, NULL);
close(gf);
close(fd);
pthread_mutex_destroy(&mutex);
return 0;
}
原图:
运行结果: