使用两个线程完成两个文件的拷贝,分支线程1完成前一半内容拷贝,分支线程2完成后一半内容的拷贝,主线程完成资源的回收
#include<myhead.h>
//定义结构体
struct file
{const char* srcfile;//背拷贝文件路径const char* destfile;//拷贝文件路径int head;//光标初始位置int size_len;//移动的大小
};/****************************计算大小**********************************/
int size_file(const char* file1,const char* file2)
{int fd1 = -1;int fd2 = -1;//打开被拷贝文件if((fd1 = open(file1,O_RDONLY))==-1){perror("open");return -1;exit(1);}//创建拷贝文件if((fd2 = open(file2,O_WRONLY|O_CREAT|O_TRUNC,0664)) == -1){perror("open");return -1;}//计算大小int len = lseek(fd1,0,SEEK_END);//关闭文件close(fd1);close(fd2);return len;
}/********************拷贝函数**************************/
//文件拷贝
void* cpy(void* arg)
{struct file file_front = *((struct file*)arg); //打开被拷贝文件int fd1 = -1;int fd2 = -1;if((fd1 = open(file_front.srcfile,O_RDONLY))==-1){perror("open");exit(1);}//打开拷贝文件if((fd2 = open(file_front.destfile,O_WRONLY)) == -1){perror("open");exit(1);}char buf[128]="";int res = -1;int num = 0;lseek(fd1,file_front.head,SEEK_SET);lseek(fd2,file_front.head,SEEK_SET);while(1){res = read(fd1,buf,sizeof(buf));num += res;if(num >= file_front.size_len||res==0){write(fd2,buf,res-(num-file_front.size_len));break;}write(fd2,buf,res);}close(fd1);close(fd2);pthread_exit(NULL);}
/**********************主函数***************************/
int main(int argc, const char *argv[])
{//判断输入是否正确if(3 != argc){printf("输入错误\n");return -1;}//计算要拷贝的文件大小,并创建目标文件int len = size_file(argv[1],argv[2]);//创建两个线程pthread_t tid1 = -1;pthread_t tid2 = -1;struct file information_front={argv[1],argv[2],0,len/2};if(pthread_create(&tid1,NULL,cpy,&information_front)){printf("tid1创建错误\n");return -1;}struct file information_rear={argv[1],argv[2],len/2,len-len/2};if(pthread_create(&tid2,NULL,cpy,&information_rear)){printf("tid2创建错误\n");return -1;}//回收线程pthread_join(tid1,NULL);pthread_join(tid2,NULL);return 0;
}
效果图:
互斥锁练习
#include<myhead.h>int money = 5000;pthread_mutex_t mutex;void* tsak(void* arg)
{while(1){//上锁pthread_mutex_lock(&mutex);money -= 50;printf("B取出50元,还剩%d元\n",money);//解锁pthread_mutex_unlock(&mutex);sleep(1);}pthread_exit(NULL);
}int main(int argc, const char *argv[])
{pthread_t tid = -1;//互斥锁初始化pthread_mutex_init(&mutex,NULL);//创建线程if(pthread_create(&tid,NULL,tsak,NULL) != 0){printf("创建线程错误\n");return -1;}while(1){//上锁pthread_mutex_lock(&mutex);money -= 100;printf("A取出100元,还剩%d元\n",money);//解锁pthread_mutex_unlock(&mutex);sleep(1);}pthread_join(tid,NULL);pthread_mutex_destroy(&mutex);return 0;
}
效果图: