• 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

  • 相关阅读:
    复利计算-做汉堡,结对2.0-复利计算再升级
    java集合
    java 封装,继承,多态基础
    购物车
    ajax
    演示
    实验四
    实验三
    构建之法6-7章读后感
    作业调度模拟程序
  • 原文地址:https://www.cnblogs.com/lianshuiwuyi/p/7506972.html
Copyright © 2020-2023  润新知