思维导图
作业
多线程实现文件拷贝,线程1拷贝一半,线程2拷贝另一半,主线程回收子线程资源。
#include <myhead.h>
typedef struct
{
const char *p1;
const char *p2;
int len;
}Fun;
int length(const char *p1,const char *p2)
{
int fd1= open(p1,O_RDONLY);
if(fd1==-1)
{
perror("open");
return -1;
}
int len = lseek(fd1,0,SEEK_END);
int fd2 = open(p2,O_WRONLY|O_CREAT|O_TRUNC,0664);
if(fd2==-1)
{
perror("open");
return -1;
}
close(fd1);
close(fd2);
return len;
}
int copy(const char *p1,const char *p2,int n,int half)
{
int fd1= open(p1,O_RDONLY);
if(fd1==-1)
{
perror("open");
return -1;
}
int fd2 = open(p2,O_WRONLY);
if(fd2==-1)
{
perror("open");
return -1;
}
lseek(fd1,n,SEEK_SET);
lseek(fd2,n,SEEK_SET);
char buff[1024];
int sum=0;
while(1)
{
int res = read(fd1,buff,sizeof(buff));
sum += res;
if(sum>half || res==0)
{
write(fd2,buff,(res-(sum-half)));
break;
}
write(fd2,buff,res);
}
close(fd1);
close(fd2);
return 0;
}
void *fun(void *a)//子线程
{
Fun *b = (Fun *)a;
int len = b->len;
copy(b->p1,b->p2,len/2,len/2);
return NULL;
}
int main(int argc, const char *argv[])
{
if(argc!=3)
{
printf("外部参数错误\n");
return -1;
}
int len = length(argv[1],argv[2]);//获取文件长度
Fun *s = malloc(sizeof(Fun));
s->p1 = argv[1];
s->p2 = argv[2];
s->len = len;
pthread_t tid;
if(pthread_create(&tid,NULL,fun,s)==-1)//主线程
{
perror("pthread_create");
return -1;
}
copy(argv[1],argv[2],0,len/2);
pthread_join(tid,NULL);//等待子线程执行
free(s);
s==NULL;
return 0;
}
互斥锁实现一遍
#include <myhead.h>
pthread_mutex_t fastmutex;
int k = 0;
void *fun(void *a)
{
pthread_mutex_lock(&fastmutex);
for(int i=0;i<500000;i++)
{
k+=1;
}
pthread_mutex_unlock(&fastmutex);
}
int main(int argc, const char *argv[])
{
pthread_mutex_init(&fastmutex,NULL);
pthread_t tid;
for(int i=0;i<10;i++)
{
if(pthread_create(&tid,NULL,fun,NULL)==-1)
{
perror("pthread_create");
return -1;
}
}
sleep(2);
printf("预想结果5000000\n");
printf("实际结果%d\n",k);
return 0;
}