Linux下实现多线程文件复制,使用<pthread.h>提供的函数:
int pthread_create(pthread_t *thread,const pthread_attr_t *restrict attr,void* (*start_routine)(void*),void *restrict arg),创建线程,
int pthread_join(pthread_t thread,void **value_ptr),回收子线程
子线程负责文件复制
void* doThread(void *arg) { Info* info = (Info*)arg; unsigned long int per = getSize(info->fromFile)/maxThread; FILE* fin = fopen(info->fromFile,"r"); FILE* fout = fopen(info->toFile,"w+"); fseek(fin,info->num*per,SEEK_SET); fseek(fout,info->num*per,SEEK_SET); char buf[4096] = {0}; int n; int sum = 0; while((n = fread(buf,1,sizeof(buf),fin)) > 0) { fwrite(buf,1,n,fout); if(info->num == (maxThread-1)) cout<<"sum = "<<sum<<" per = "<<per<<endl; sum += n; if(sum > per) break; memset(buf,0,sizeof(buf)); } fclose(fin); fclose(fout); return NULL; }
其中struct Info结构原型
struct Info { char* fromFile; //源文件 char* toFile; //目标文件 int num; //第几个线程 };
完整代码详见GitHub地址:https://github.com/MasterMeng/mult_pthread_copy