多线程文件拷贝
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>
#include <assert.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
pthread_mutex_t mutex;
char *src_addr=NULL;
char *new_addr=NULL;
int count;
void *pth_work(void *arg)
{
int i=*(int *)arg;
pthread_mutex_lock(&mutex);//上锁
printf("%ld子线程开始拷贝.....\n",pthread_self());
memcpy(new_addr+i*count,src_addr+i*count,count);
pthread_mutex_unlock(&mutex);//解锁
}
int main(int argc, char **argv)
{
int fp=open(argv[1],0);
if(fp<0)
{
printf("文件打开失败\n");
return 0;
}
int new_fp=open(argv[2],O_RDWR|O_CREAT,0666);
if(new_fp<0)
{
printf("新文件打开失败\n");
return 0;
}
//获取文件大小
struct stat statbuf;
fstat(fp,&statbuf);
//设置新文件大小
ftruncate(new_fp,statbuf.st_size);
//内存映射
src_addr=mmap(NULL,statbuf.st_size,PROT_READ,MAP_PRIVATE,fp,0);
new_addr=mmap(NULL,statbuf.st_size,PROT_READ|PROT_WRITE,MAP_SHARED,new_fp,0);
close(fp);
close(new_fp);
//内存拷贝
count=statbuf.st_size/5;
int remain=statbuf.st_size%5;
//创建普通锁
pthread_mutex_init(&mutex,NULL);
pthread_t pthid;
int i=0;
for(i=0;i<5;i++)
{
pthread_create(&pthid,NULL,pth_work,(void *)&i);
sleep(1);
}
while(1)
{
pthread_mutex_lock(&mutex);//上锁
memcpy(new_addr+i*count,src_addr+i*count,remain);
pthread_mutex_unlock(&mutex);//解锁
//取消映射
munmap(src_addr,statbuf.st_size);
munmap(new_addr,statbuf.st_size);
exit(0);//结束进程
}
}
标签:count,文件,include,addr,int,mutex,pthread,拷贝,多线程
From: https://www.cnblogs.com/yesiming/p/18045615