求大侠帮忙见见多线程拷贝文件代码出错
求大侠帮忙看看多线程拷贝文件代码出错
这段代码运行后把一个1.2G的文件复制成314M样子的文件,看了很久没看出问题所在,请大侠帮忙看看问题在哪?小弟谢谢大家了
------解决思路----------------------
这个应该是要加线程锁
#include<stdio.h>
#include<unistd.h>
#include<fcntl.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<pthread.h>
#include<string.h>
#define SPATH "/root/Desktop/pthread/1G.rar"
#define DPATH "/root/Desktop/1G1.rar"
#define SIZE 1024
#define NUM_THREAD 5
int get_size(char *filename);
void* threadCp(void *arg);
int i_thread=0;
typedef struct Cp_INFO
{
int i_num;
}info;
int get_size(char *filename)
{
struct stat st;
memset(&st,0,sizeof(st));
stat(filename,&st);
return st.st_size;
}
void* threadCp(void *arg)
{
info info1=*((info*)arg);
int in=0;
int out=0;
int size=0;
int rlen=0;
char buffer[SIZE]={'\0'};
in=open(SPATH,O_RDONLY);
if(-1==in)
{
printf("Open File error!\n");
}
out=creat(DPATH,O_WRONLY);
if(-1==out)
{
printf("Create File error!\n");
}
size=get_size(SPATH);
printf("i_num=%d\n",info1.i_num);
printf("size*i_thread/NUM_THREAD=%d\n",size*i_thread/NUM_THREAD);
lseek(in,size*i_thread/NUM_THREAD,SEEK_SET);
lseek(out,size*i_thread/NUM_THREAD,SEEK_SET);
int len=0;
int total=0;
while((rlen=read(in,buffer,sizeof(buffer)))>0)
{
write(out,buffer,rlen);
total+=rlen;
if(total>size/NUM_THREAD)
{
break;
}
}
close(in);
close(out);
}
int main()
{
pthread_t pid[NUM_THREAD];
info c_info;
int i=0;
int j=0;
/*int out=creat(DPATH,S_IWUSR);
if(-1==out)
{
printf("Create File error!\n");
return -1;
}*/
for(i=0;i<NUM_THREAD;i++)
{
i_thread=i;
c_info.i_num=i;
printf("info_inum=%d\n",c_info.i_num);
pthread_create(&pid[i],NULL,threadCp,(void*)&c_info);
}
for(j=0;j<NUM_THREAD;j++)
{
pthread_join(pid[j],NULL);
}
printf("copy file finish!\n");
return 0;
}
这段代码运行后把一个1.2G的文件复制成314M样子的文件,看了很久没看出问题所在,请大侠帮忙看看问题在哪?小弟谢谢大家了
------解决思路----------------------
这个应该是要加线程锁