//demo1 --- 以下为第一版代码,实现基本功能,存在缺陷
// 代码中使用全局变量作为同步手段,如果文件很大,然后CPU很忙,线程很多,由于变量赋值在汇编层面不是
// 原子的,所以最终结果会出现误差,复现手段:“把buff调到2,启动线程设置50+,目标文件50M以上”
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <fcntl.h>
#include <errno.h>
int fd_src;
int fd_des;
int flag=1;
void cp(void)
{
int cnt =0;
char buff[10];
memset(buff,0x00,10);
while(1)
{
if(flag!=1) continue;
flag=0;
cnt = read(fd_src,buff,10);
if(cnt==0) break;
write(fd_des,buff,cnt);
flag=1;
}
pthread_exit(0);
}
void do_job(int thread_num)
{
pthread_t tid[thread_num];
while(thread_num--)
{
pthread_create(&tid[thread_num],NULL,(void *)cp,NULL);
}
sleep(5);
}
int main(int argc,char ** argv)
{
char * src_path=NULL;
char * des_path=NULL;
int thread_num=0;
if(argc!=4)
{
printf("argu num must be 4\n");
return -1;
}
thread_num = atoi(argv[3]);
src_path=(char *)malloc(sizeof(argv[1]));
des_path=(char *)malloc(sizeof(argv[2]));
memcpy(src_path,argv[1],sizeof(argv[1]));
memcpy(des_path,argv[2],sizeof(argv[2]));
printf("copy file %s to %s \n",src_path,des_path);
fd_src = open(src_path,O_RDONLY);
if(fd_src== -1)
{
perror("open src file error\n");
return -1;
}
fd_des = open(des_path,O_RDWR|O_CREAT);
if(fd_des == -1)
{
perror("open des file error\n");
return -1;
}
do_job(thread_num);
return 0;
}
//demo2 --- 以下为第二版代码,保证了功能的正确性,使用互斥量作为同步手段
// 需要主线程等待子线程终止的代码,下一版再调整,目前先用sleep代替
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <fcntl.h>
#include <errno.h>
int fd_src;
int fd_des;
pthread_mutex_t flag;
void cp(void)
{
int cnt =0;
char buff[10];
memset(buff,0x00,10);
while(1)
{
pthread_mutex_lock(&flag);
cnt = read(fd_src,buff,10);
if(cnt==0)
{
pthread_mutex_unlock(&flag);
break;
}
write(fd_des,buff,cnt);
pthread_mutex_unlock(&flag);
}
pthread_exit(0);
}
void do_job(int thread_num)
{
pthread_t tid[thread_num];
while(thread_num--)
{
pthread_create(&tid[thread_num],NULL,(void *)cp,NULL);
}
sleep(5);
}
int main(int argc,char ** argv)
{
char * src_path=NULL;
char * des_path=NULL;
int thread_num=0;
pthread_mutex_init(&flag,NULL);
if(argc!=4)
{
printf("argu num must be 4\n");
return -1;
}
thread_num = atoi(argv[3]);
src_path=(char *)malloc(sizeof(argv[1]));
des_path=(char *)malloc(sizeof(argv[2]));
memcpy(src_path,argv[1],sizeof(argv[1]));
memcpy(des_path,argv[2],sizeof(argv[2]));
printf("copy file %s to %s \n",src_path,des_path);
fd_src = open(src_path,O_RDONLY);
if(fd_src== -1)
{
perror("open src file error\n");
return -1;
}
fd_des = open(des_path,O_RDWR|O_CREAT);
if(fd_des == -1)
{
perror("open des file error\n");
return -1;
}
do_job(thread_num);
pthread_mutex_destory(&flag);
return 0;
}
/******************总结**********************/
多线程拷贝文件无法提高拷贝效率,同时还因为调度问题降低效率
目前还没有想出什么好办法通过多线程来提高拷贝效率