1.实现一个线程打印,一个线程反转字符串
char str[]="123456";
void* print(void* arg){
while(1){
printf("子线程print_打印:%s\n",(char *)arg);
sleep(1);
}
}
void* reserve(void* arg){
char *start;
char *end;
while(1){
start=str;
end=str;
while(*end!='\0'){
end++;
}
end--;
while(start<end){
char temp=*start;
*start=*end;
*end=temp;
start++;
end--;
}
strcpy((char *)arg,str);
//printf("reserve:%s\n",str);
sleep(1);
}
}
void test_pthread_string(){
char *s=str;
pthread_t pth_n;
pthread_create(&pth_n,NULL,reserve,(void *)s);
//sleep(1);
//printf("main_pthread:%s\n",s);
pthread_t pth_p;
pthread_create(&pth_p,NULL,print,(void*)s);
while(1){
sleep(1);
// printf("main=%s\n",str);
}
}
2.实现线程拷贝图片
char c;
void* copy_h(void* arg){
int size=((int*)arg)[2];
lseek(((int*)arg)[0],0,SEEK_SET);
lseek(((int*)arg)[1],0,SEEK_SET);
for(int i=0;i<size/2;i++){
read(((int*)arg)[0],&c,1);
write(((int*)arg)[1],&c,1);
}
((int*)arg)[3]=1;
}
char d;
void *copy_t(void* arg){
int size=((int*)arg)[2];
int isodd=size%2;
lseek(((int*)arg)[0],size/2,SEEK_SET);
lseek(((int*)arg)[1],size/2,SEEK_SET);
for(int i=0;i<size/2+isodd;i++){
read(((int*)arg)[0],&d,1);
write(((int*)arg)[1],&d,1);
}
((int*)arg)[4]=1;
}
void test_cp_pic_bythread(char *path_src,char *path_dest){
int fd_src=open(path_src,O_RDONLY);
if(fd_src<0){
perror("src_open");
return;
}
int fd_dest=open(path_dest,O_WRONLY|O_CREAT,0777);
if(fd_dest<0){
perror("src_open");
return;
}
struct stat s;
stat(path_src,&s);
int arg[10];
arg[0]=fd_src;
arg[1]=fd_dest;
arg[2]=s.st_size;
arg[3]=0;
arg[4]=0;
pthread_t pth_h;
pthread_create(&pth_h,NULL,copy_h,(void*)arg);
sleep(1);
pthread_t pth_t;
pthread_create(&pth_t,NULL,copy_t,(void*)arg);
while(1){
if(arg[3]==1&&arg[4]==1){
close(fd_src);
close(fd_dest);
printf("拷贝完成\n");
break;
}
sleep(1);
}
}