多线程文件分割实现原理,根据分割文件个数或分割后的文件大小确定启动的线程个数,在各个子线程启动之前需要确定每一个线程在原始文件中读取的开始位置(或称为文件偏移量),之后各个子线程独立地并行工作,从原始文件中读出数据,并写入分割后的文件。
#include
#include
#include
#include
#include
typedef struct SplitInfo{
gchar* name;
guint index;
gulong offset;
gulong length;
}SplitInfo;
#define NUM 10
gpointer split_proc(gpointer data);
int main(int argc,char** argv){
GThread* threads[NUM];
SplitInfo si[NUM];
int i = 0;
g_thread_init(NULL);
struct stat file_info;
stat(argv[1],&file_info);
int blocks = file_info.st_size / NUM;
if(file_info.st_size / NUM) blocks++;
for(i = 0; i < blocks;i++){
si[i].name = argv[1];
si[i].index = i;
si[i].offset = i * blocks;
si[i].length = blocks;
threads[i] = g_thread_create(split_proc,&si[i],TRUE,NULL);
}
for(i = 0;i < NUM;i++){
g_thread_join(threads[i]);
}
return 0;
}
#define WRITE_BLOCK 256
gpointer split_proc(gpointer data){
SplitInfo* info = (SplitInfo*)data;
guint len = 0;
gchar buf[WRITE_BLOCK];
guint i = 0;
FILE* fp = fopen(info->name,"rb");
if(fp == NULL) return NULL;
fseek(fp,info->offset,SEEK_SET);
gchar sp_name[256] = {0};
g_sprintf(sp_name,"%s.%04d",info->name,info->index);
FILE* sp = fopen(sp_name,"wb");
if(sp == NULL) return 0;
for(i = 0; i < info->length;i += WRITE_BLOCK){
len = fread(buf,1,WRITE_BLOCK,fp);
fwrite(buf,1,len,sp);
}
fclose(sp);
fclose(fp);
return NULL;
}