9.11 IO进程

作业1:

#include <myhead.h>
void*copy(void* arg){
	int fd=open("/mnt/hgfs/Ubuntushare/preview.gif",O_RDWR);//要复制的图片
	int fd2=open("./2.gif",O_RDWR|O_APPEND);//复制到1.jpg
	ssize_t res=0;//接收read的返回值
	char buf[20]="";
	lseek(fd2,*(int*)arg,SEEK_SET);
	while(1){
		res=read(fd,buf,sizeof(buf));
		if(res==0){
			break;
		}
		write(fd2,buf,res);
	}
	close(fd2);
}
int main(int argc, const char *argv[])
{
	int fd=open("./2.gif",O_RDWR|O_CREAT|O_APPEND,0664);
	close(fd);
	int fd1=open("/mnt/hgfs/Ubuntushare/preview.gif",O_RDWR);//要复制的图片
	int fd2=open("./2.gif",O_RDWR|O_APPEND);//复制到1.jpg
	ssize_t res=0;//接收read的返回值
	off_t len=lseek(fd1,0,SEEK_END);
	ssize_t sum=0;//一共读了多少字节
	char buf[20]="";
	//主线程复制前面一半
	lseek(fd,0,SEEK_SET);
	while(1){
		res=read(fd1,buf,sizeof(buf));
		sum+=res;
		if(sum<=(len/2))
		{
			write(fd2,buf,res);
		}
		else{
			write(fd2,buf,res);
			break;
		}
	}
	pthread_t tid;//创建分支线程
	int len1=lseek(fd1,0,SEEK_CUR);
	if(pthread_create(&tid,NULL,copy,(void*)&len1)!=0){
		fprintf(stderr,"fail _%d_\n",__LINE__);
	}
	pthread_join(tid,NULL);
	close(fd1);
	close(fd2);
	return 0;
}

作业2:

#include <myhead.h>
char buf[]="1234567";
void* allturn(void* arg)
{
	while(1){
		if(*(int*)arg==1){
			for(int i=0;i<(sizeof(buf)-1)/2;i++){
				char t=buf[i];
				buf[i]=buf[sizeof(buf)-2-i];
				buf[sizeof(buf)-2-i]=t;
			}
			*(int*)arg=0;
		}
	}
}
int main(int argc, const char *argv[])
{
	int t=0;
	pthread_t tid;
	if(pthread_create(&tid,NULL,allturn,(void*)&t)!=0){
		fprintf(stderr,"fail_%d_\n",__LINE__);
		return -1;
	}
	while(1){
		if(t==0){
			if(strcmp(buf,"7654321")==0||strcmp(buf,"1234567")==0)
			{
				printf("%s\n",buf);
			}	
			t=1;
		}
	}
	return 0;
}
1234567
7654321
1234567
7654321
1234567
7654321
1234567
7654321
1234567
7654321
1234567
7654321
1234567
7654321
1234567
7654321
1234567
7654321
1234567
7654321
1234567
7654321

错误原因:线程之间是时间片轮询机制,在线程B未完全逆置时,且时间片完,CPU切换到A线程,就会出现乱序

X-mind:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值