zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    IList扩展
    WPF 路由事件
    WPF 属性值绑定、转换
    WPF 生命周期
    App.config 动态编辑
    Oracle Package的全局变量与Session
    AES对数据进行加密与解密
    OracleAES加密
    AES加解密程序的实现
    Oracle的AES加密与解密用法
  • 原文地址:https://www.cnblogs.com/lianshuiwuyi/p/7506972.html
Copyright © 2011-2022 走看看