Linux下多線程復制文件(C)


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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM