创建两个线程:其中一个线程拷贝前半部分,另一个线程拷贝后半部分。
只允许开一份资源,且用互斥锁方式实现。 提示:找临界区--->找临界资源。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <head.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
pthread_mutex_t mutex;
struct file
{
int fd_r;
int fd_w;
off_t size;
};
void *callback_A(void *arg) //void *arg = &fp
{
int fd_r = ((struct file*)arg)->fd_r;
int fd_w = ((struct file*)arg)->fd_w;
off_t size = ((struct file*)arg)->size;
//上锁
pthread_mutex_lock(&mutex);
lseek(fd_r, 0, SEEK_SET);
lseek(fd_w, 0, SEEK_SET);
char c = 0;
for(int i=0; i<size/2; i++)
{
read(fd_r, &c, 1);
write(fd_w, &c, 1);
}
printf("前半部分拷贝完毕\n");
//解锁
pthread_mutex_unlock(&mutex);
pthread_exit(NULL);
}
void *callback_B(void *arg) //void *arg = &fp
{
int fd_r = ((struct file*)arg)->fd_r;
int fd_w = ((struct file*)arg)->fd_w;
off_t size = ((struct file*)arg)->size;
//上锁
pthread_mutex_lock(&mutex);
lseek(fd_r, size/2, SEEK_SET);
lseek(fd_w, size/2, SEEK_SET);
char c = 0;
for(int i=size/2; i<size; i++)
{
read(fd_r, &c, 1);
write(fd_w, &c, 1);
}
printf("后半部分拷贝完毕\n");
//解锁
pthread_mutex_unlock(&mutex);
pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
//申请一个互斥锁
pthread_mutex_init(&mutex,NULL);
//两个线程在拷贝前,确保文件存在,且是清空状态
int fd_w = open("copy.png", O_WRONLY|O_CREAT|O_TRUNC, 0644);
if(fd_w < 0)
{
ERR_MSG("open");
return -1;
}
//以读的方式打开源文件
int fd_r = open("666.png", O_RDONLY);
if(fd_r < 0)
{
ERR_MSG("open");
return -1;
}
off_t size = lseek(fd_r, 0, SEEK_END);
struct file fp;
fp.fd_r = fd_r;
fp.fd_w = fd_w;
fp.size = size;
pthread_t tid1,tid2; //创建两个线程
//创建一个A线程
if(pthread_create(&tid1,NULL,callback_A,(void *)&fp) != 0)
{
fprintf(stderr,"pthread_create failed __%d__",__LINE__);
return -1;
}
//创建一个B线程
if(pthread_create(&tid2,NULL,callback_B,(void *)&fp) != 0)
{
fprintf(stderr,"pthread_create failed __%d__",__LINE__);
return -1;
}
//阻塞等待分支线程退出
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
//销毁互斥锁
pthread_mutex_destroy(&mutex);
close(fd_r);
close(fd_w);
return 0;
}
结果为: