迅雷這類下載工具大家都用過,它背後靠的就是多線程下載,而多線程檔案拷貝正是多線程下載的基礎。下面是完整實作:
//copyfile.cc
#include <iostream>
#include <cstring>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <pthread.h>
using namespace std;
/************************************
* 使用指定線程實現從檔案的拷貝
* 建立時間:2011.07.28 修改時間:2011.07.29 作者:hahaya
************************************/
//最大使用的線程數
const int MAX_THREADS = 5;
typedef struct TAG_INFO
{
char *fromfile; //來源位址
char *tofile; //目的位址
int num; //啟動的第 i-1 個線程
} info;
//st_size 的型別為 __off_t
int get_size(const char *filename)
{
struct stat st;
memset(&st, 0, sizeof(st));
stat(filename, &st);
return st.st_size;
}
void* threadDL(void *param)
{
info info1 = *((info*)param);
FILE *fin = fopen(info1.fromfile, "r+");
FILE *fout = fopen(info1.tofile, "w+");
int size = get_size(info1.fromfile);
//將檔案指針分別設置在每個線程要讀和寫的位置
fseek(fin, size*(info1.num)/MAX_THREADS, SEEK_SET);
fseek(fout, size*(info1.num)/MAX_THREADS, SEEK_SET);
char buff[1024] = {'\0'};
int len = 0;
int total = 0;
while((len = fread(buff, 1, sizeof(buff), fin)) > 0)
{
fwrite(buff, 1, len, fout);
total += len;
//每個線程要讀寫的資料量約等於總大小除以線程數,超過就停止
//可能會多寫入一些資料,下一次寫入時會覆蓋掉,所以不用擔心
if(total > size/MAX_THREADS)
{
break;
}
}
fclose(fin);
fclose(fout);
}
int main(int argc, char *argv[])
{
//先建立一個與來源檔同樣大小的檔案
creat(argv[2], 0777);
truncate(argv[2], get_size(argv[1]));
pthread_t pid[MAX_THREADS];
info info1;
//啟動指定數量線程的線程
for(int i = 0; i < MAX_THREADS; i++)
{
memset(&info1, 0, sizeof(info1));
info1.fromfile = argv[1];
info1.tofile = argv[2];
info1.num = i;
pthread_create(&pid[i], NULL, threadDL, (void *)&info1);
}
//等待線程結束
for(int j = 0; j < MAX_THREADS; j++)
{
//pthread_join 不能寫在建立線程的 for 迴圈裡,
//否則會變成建立第一個就等它結束才建立第二個
pthread_join(pid[j], NULL);
}
cout << "file copy success......" << endl;
return 0;
}
執行截圖:
複製後的檔案是完整的,可以正常解壓縮,如下圖。
思路很直觀:先用 creat 加 truncate 預先撐出一個同大小的目標檔,再讓每個線程各自定位到 size × num / MAX_THREADS 的偏移處,分頭讀寫自己那一段,最後 join 全部線程即可。