1> 使用两个线程完成两个文件的拷贝,主线程拷贝前一半内容,子线程拷贝后一半内容,并且主线程要阻塞回收子线程资源
#include<myhead.h>
//定义一个结构体
typedef struct {
FILE* src;
FILE* dest;
} Copy;
void *task1(void *arg)
{
Copy* args = (Copy*)arg; //强转为结构体类型
char buf[10]="";
fseek(args->src,0,SEEK_END); //移动光标到结尾
int len=ftell(args->src); //计算文件长度
fseek(args->src,len/2,SEEK_SET); //移动光标至文件1/2处
fread(buf,1,len-len/2,args->src);
fwrite(buf,1,len-len/2,args->dest);
pthread_exit(NULL); //退出线程
}
int main(int argc, const char *argv[])
{
FILE *fp;
FILE *fp1;
//判断并打开文件
if((fp=fopen(argv[1],"r"))==NULL||(fp1=fopen(argv[2],"w"))==NULL)
{
perror("fopen error");
return -1;
}
//定义一个结构体变量并初始化
Copy args;
args.src = fp;
args.dest = fp1;
pthread_t tid1;//创建一个线程
if(pthread_create(&tid1,NULL,task1,&args))
{
printf("失败\n");
return -1;
}
fseek(fp,0,SEEK_END);
int len=ftell(fp);
fseek(fp,0,SEEK_SET);
char buf[10]="";
fread(buf,1,len/2,fp);
fwrite(buf,1,len/2,fp1);
pthread_join(tid1,NULL);//阻塞等待线程结束并回收
fclose(fp);
fclose(fp1);//关闭文件
printf("copyfiles successfully\n");
return 0;
}
2> 使用三个进程完成两个文件的拷贝,主线程拷贝前三分之一,子线程1拷贝中间三分之一,子线程2拷贝后三分之一,主线程要设置两个子线程为分离态
#include<myhead.h>
//定义结构体
typedef struct {
FILE* src;
FILE* dest;
} Copy;
void *task1(void *arg)
{
Copy* args = (Copy*)arg;//强转成结构体类型
char buf[30]="";
fseek(args->src,0,SEEK_END);//移动光标至文件末尾
int len=ftell(args->src);//计算文件长度
fseek(args->src,len/3,SEEK_SET);//移动光标到文件1/3处
fread(buf,1,len/3,args->src);
fwrite(buf,1,len/3,args->dest);
pthread_exit(NULL);//退出当前线程
}
void *task2(void *arg)
{
sleep(1);
Copy* args = (Copy*)arg;
char buf[30]="";
fseek(args->src,0,SEEK_END);
int len=ftell(args->src);
fseek(args->src,len/3*2,SEEK_SET);
fread(buf,1,len-len/3*2,args->src);
fwrite(buf,1,len-len/3*2,args->dest);
pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
FILE *fp;
FILE *fp1;
if((fp=fopen(argv[1],"r"))==NULL||(fp1=fopen(argv[2],"w"))==NULL)
{
perror("fopen error");
return -1;
}
//定义一个结构体变量并初始化
Copy args;
args.src = fp;
args.dest = fp1;
//创建两个线程
pthread_t tid1,tid2;
if(pthread_create(&tid1,NULL,task1,&args))
{
printf("失败\n");
return -1;
}
if(pthread_create(&tid2,NULL,task2,&args))
{
printf("失败\n");
return -1;
}
fseek(fp,0,SEEK_END);
int len=ftell(fp);
fseek(fp,0,SEEK_SET);
char buf[30]="";
fread(buf,1,len/3,fp);
fwrite(buf,1,len/3,fp1);
sleep(2);
pthread_detach(tid1);//线程分离
pthread_detach(tid2);
fclose(fp);
fclose(fp1);
printf("copyfiles successfully\n");
return 0;
}
3、思维导图