创建3个线程,一个子线程拷贝文件的前一半,一个子线程拷贝后一半文件,主线程回收子线程资源。
#include <myhead.h>
//将源文件1.txt拷贝到目标文件2.txt
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_CREAT|O_TRUNC,0664);
if(fd1==-1)
{
perror("open1");
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;
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];
int sum=0;
while(1)
{
int res = read(fd1,buff,sizeof(buff));
sum+=res;
if(sum>=len||res==0)
{
write(fd2,buff,res-(sum-len));
break;
}
write(fd2,buff,res);
}
return 0;
}
void *fun1(void *aaa)
{
pthread_exit(NULL);
}
void *fun2(void *aaa)
{
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;
int k1 = pthread_create(&tid1,NULL,fun1,NULL);
int k2 = pthread_create(&tid2,NULL,fun2,NULL);
if(k1==0)
{
copy_file(argv[1],argv[2],0,len/2);
}
if(k2==0)
{
copy_file(argv[1],argv[2],len/2,(len-len/2));
}
pthread_detach(tid1);
pthread_detach(tid2);
return 0;
}
使用无名信号量实现循环输出 春、夏、秋、冬。
#include<myhead.h>
//春 夏 秋 冬
sem_t sem1,sem2,sem3,sem4;
void *fun1(void *ggg)
{
while(1)
{
sem_wait(&sem4);
printf("春\t");
fflush(stdout);
sem_post(&sem2);
}
pthread_exit(NULL);
}
void *fun2(void *ggg)
{
while(1)
{
sem_wait(&sem2);
printf("夏\t");
fflush(stdout);
sem_post(&sem3);
}
pthread_exit(NULL);
}
void *fun3(void *ggg)
{
while(1)
{
sem_wait(&sem3);
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);
}
}
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(&sem4,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;
}
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
pthread_join(tid3,NULL);
pthread_join(tid4,NULL);
return 0;
}