作业一:创建3个线程,一个子线程拷贝文件的前一半,一个子线程拷贝后一半文件,主线程回收子线程资源。
#include <myhead.h>
int get_len(const char *p1,const char *p2)
{
int fd1=open(p1,O_RDONLY);
if(fd1==-1)
{
perror("open1");
return -1;
}
int fd2=open(p2,O_WRONLY|O_TRUNC|O_CREAT,0664);
if(fd2==-1)
{
perror("open2");
return -1;
}
int len=lseek(fd1,0,SEEK_END);
close(fd1);
close(fd2);
return len;
}
int copy_file(const char *p1,const char *p2,int start,int len)
{
int fd1,fd2,sum=0;
fd1=open(p1,O_RDONLY);
if(fd1==-1)
{
perror("open1");
return -1;
}
fd2=open(p2,O_WRONLY);
if(fd2==-1)
{
perror("open2");
return -1;
}
lseek(fd1,start,SEEK_SET);
lseek(fd2,start,SEEK_SET);
char buff[1024];
while(1)
{
int res=read(fd1,buff,sizeof(buff));
sum+=res;
if(sum>=len||res==0)
{
res=res-(sum-len);
write(fd2,buff,res);
break;
}
write(fd2,buff,res);
}
return 0;
}
void *fun1(void *arg)
{
int len=*(int*)arg;
copy_file("copy.txt","1.txt",0,len/2);
pthread_exit(NULL);
}
void *fun2(void *arg)
{
int len=*(int*)arg;
copy_file("copy.txt","1.txt",len/2,len-len/2);
pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
if(argc!=3)
{
printf("外部传参错误\n");
return-1;
}
int len=get_len(argv[1],argv[2]);
pthread_t tid1,tid2;
if(pthread_create(&tid1,NULL,fun1,&len)!=0)
{
perror("ptcreat1");
return -1;
}
if(pthread_create(&tid2,NULL,fun2,&len)!=0)
{
perror("ptcreat2");
return -1;
}
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
return 0;
}
作业二:使用无名信号量实现循环输出 春、夏、秋、冬。
ubuntu@ubuntu:day5$ cat zy2.c
#include <myhead.h>
sem_t sem1,sem2,sem3,sem4;
void *fun1(void *ggg)
{
while(1)
{
sem_wait(&sem4);
printf("春\t");
fflush(stdout);
sem_post(&sem3);
}
pthread_exit(NULL);
}
void *fun2(void *ggg)
{
while(1)
{
sem_wait(&sem3);
printf("夏\t");
fflush(stdout);
sem_post(&sem2);
}
pthread_exit(NULL);
}
void *fun3(void *ggg)
{
while(1)
{
sem_wait(&sem2);
printf("秋\t");
fflush(stdout);
sem_post(&sem1);
}
pthread_exit(NULL);
}
void *fun4(void *ggg)
{
while(1)
{
sem_wait(&sem1);
printf("冬\t");
fflush(stdout);
sem_post(&sem4);
}
pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
pthread_t tid1,tid2,tid3,tid4;
sem_init(&sem1,0,0);
sem_init(&sem2,0,0);
sem_init(&sem3,0,0);
sem_init(&sem3,0,1);
if(pthread_create(&tid1,NULL,fun1,NULL)!=0)
{
perror("ptcreat1");
return -1;
}
if(pthread_create(&tid2,NULL,fun2,NULL)!=0)
{
perror("ptcreat2");
return -1;
}
if(pthread_create(&tid3,NULL,fun3,NULL)!=0)
{
perror("ptcreat3");
return -1;
}
if(pthread_create(&tid4,NULL,fun4,NULL)!=0)
{
perror("ptcreat4");
return -1;
}
sem_destroy(&sem1);
sem_destroy(&sem2);
sem_destroy(&sem3);
sem_destroy(&sem4);
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
pthread_join(tid3,NULL);
pthread_join(tid4,NULL);
return 0;
}
x-mind