- 论坛徽章:
- 0
|
#include <iostream>
#include <fcntl.h>
#include <unistd.h>
#include <assert.h>
#include <sys/time.h>
#include <sys/stat.h>
#include <pthread.h>
using namespace std;
const int maxbuff = 4096;
bool file_exist(const char *file)
{
int fd;
assert(file != NULL);
fd = open(file, O_RDONLY);
if(fd < 0){
return false;
}else{
close(fd);
return true;
}
}
double get_current_time(void)
{
struct timeval time[1];
if(gettimeofday(time, 0) < 0) return -1;
return (double)time->tv_sec + (double)time->tv_usec / 1000000;
}
struct task
{
char *srcfile;
char *desfile;
off_t start;
off_t length;
mode_t stmode;
};
void *thread_copy(void *arg)
{
task *threadtask = (task*)arg;
int src,des;
if ((src = open(threadtask->srcfile, O_RDONLY)) == -1)
{
cerr<<"cannot open src file in thread"<<endl;
pthread_exit((void *)-1);
}
if ((des = open(threadtask->desfile, O_WRONLY)) == -1)
{
cerr<<"cannot open dest file"<<endl;
pthread_exit((void *)-1);
}
lseek(src,threadtask->start,SEEK_SET);
lseek(des,threadtask->start,SEEK_SET);
int n;
char buff[maxbuff+1];
int len = threadtask->length;
int readlen = min(len,maxbuff);
while ((readlen > 0) && (n = read(src,buff,readlen)) > 0)
{
if (write(des,buff,n) != n)
cerr<<"error write"<<endl;
len -= n;
readlen = min(len,maxbuff);
}
close(src);
close(des);
}
int main(int argc,char *argv[])
{
int srcfd,desfd;
double start,end;
struct stat file_stat;
if (argc < 4)
{
cerr<<"arg error"<<endl;
return -1;
}
if ((srcfd = open(argv[1], O_RDONLY)) == -1)
{
cerr<<"cannot open src file"<<endl;
return -1;
}
fstat(srcfd,&file_stat);
if (file_exist(argv[2]))
{
cerr<<"exist"<<endl;
return -1;
}
if ((desfd = open(argv[2], O_WRONLY | O_CREAT | O_TRUNC, file_stat.st_mode)) == -1)
{
cerr<<"cannot open dest file"<<endl;
return -1;
}
cout<<"file size "<<file_stat.st_size<<endl;
int nthread = atoi(argv[3]);
pthread_t *ptid = new pthread_t[nthread];
task *taskid = new task[nthread];
int thlength = file_stat.st_size/nthread;
start = get_current_time();
for (int i = 0; i < nthread; i++)
{
taskid.srcfile = argv[1];
taskid.desfile = argv[2];
taskid.length = thlength;
taskid.start = thlength*i;
taskid.stmode = file_stat.st_mode;
}
taskid[nthread-1].length = file_stat.st_size-thlength*(nthread-1);
int err;
for (int i = 0; i < nthread; i++)
{
err = pthread_create(&ptid,NULL,thread_copy,(void *)(&taskid));
if (err != 0)
{
cerr<<"create thread error"<<endl;
exit(1);
}
}
for (int i = 0; i < nthread; i++)
{
pthread_join(ptid,NULL);
}
end = get_current_time();
cout<<"cost "<<end-start<<" s"<<endl;
delete []ptid;
delete []taskid;
close(srcfd);
close(desfd);
return 0;
}
用的电脑是4核cpu,结果速度比单线程的慢,而且文件越大,慢的越狠。。。 |
|