IO 线程 习题

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);
	}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值