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

转载于:https://www.cnblogs.com/lianshuiwuyi/p/7506972.html

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值