用两个线程拷贝一张图片,要求A线程铂贝前半部分,B线程拷贝后半部分;提示:找到临界资源,临界区,上锁解锁即可;
#include<stdio.h>
#include<pthread.h>
#include<string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
pthread_mutex_t mutex;
int fd_r;
int fd_w;
off_t size;
int flag;
void* fun1(void* arg)
{
int i;
char c;
off_t offset=0;
for(i=0;i<size/2;i++)
{
pthread_mutex_lock(&mutex);
lseek(fd_r,offset,SEEK_SET);
lseek(fd_w,offset,SEEK_SET);
read(fd_r,&c,1);
write(fd_w,&c,1);
offset=lseek(fd_r,0,SEEK_CUR);
pthread_mutex_unlock(&mutex);
}
printf("前面一半拷贝成功\n");
pthread_exit(NULL);
}
void* fun2(void* arg)
{
flag=size%2==0?0:1;
int i=0;
char c;
off_t offset=size/2;
for(i=0;i<size/2+flag;i++)
{
pthread_mutex_lock(&mutex);
lseek(fd_r,offset,SEEK_SET);
lseek(fd_w,offset,SEEK_SET);
read(fd_r,&c,1);
write(fd_w,&c,1);
offset=lseek(fd_r,0,SEEK_CUR);
pthread_mutex_unlock(&mutex);
}
printf("后一半拷贝成功\n");
pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
//以读的方式打开源文件
fd_r = open("1.png", O_RDONLY);
if(fd_r < 0)
{
perror("open");
//return -1;
}
//以写的方式打开目标文件
fd_w = open("2.png", O_WRONLY|O_CREAT|O_TRUNC, 0664);
if(fd_w < 0)
{
perror("open");
return -1;
}
//计算文件大小
size = lseek(fd_r, 0, SEEK_END);
printf("size = %ld \n", size);
//创建互斥锁,并初始化
if(pthread_mutex_init(&mutex, NULL) != 0)
{
perror("pthread_mutex_init");
return -1;
}
printf("mutex_init success\n");
//创建一个线程,拷贝一半
pthread_t tid_a;
if (pthread_create(&tid_a,NULL,fun1,NULL)!=0)
{
perror("thread_create_a");
return -1;
}
//创建一个线程,拷贝另一半
pthread_t tid_b;
if (pthread_create(&tid_b,NULL,fun2,NULL)!=0)
{
perror("thread_create_b");
return -1;
}
printf("线程创建成功\n");
pthread_join(tid_a, NULL);
pthread_join(tid_b, NULL);
//销毁互斥锁
pthread_mutex_destroy(&mutex);
//关闭文件
close(fd_r);
close(fd_w);
return 0;
}
结果