12.7整理



有道云笔记

#include <myhead.h>
void *task_one(void *arg)
{
	int fd1=open("./text",O_RDONLY);
	if(fd1<0)
	{
		perror("open");
		return NULL;
	}
	int fd2=open("./1text",O_WRONLY);
	if(fd2<0)
	{
		perror("open");
		return NULL;
	}
	int len=lseek(fd1,0,SEEK_END);
	
	lseek(fd1,0,SEEK_SET);
	lseek(fd2,0,SEEK_SET);
	char a[128];
	int i;
	int sum=0;
	int res=0;
	while(1)
	{
		res=read(fd1,a,sizeof(a));
		sum=sum+res;
		if(res==0|sum>=(len/2))
		{
			write(fd2,a,res-(sum-len/2));
			break;
		}
		write(fd2,a,res);

	}
	close(fd1);
	close(fd2);

}
void *task_two(void *arg)
{
	int fd1=open("./text",O_RDONLY);
	if(fd1<0)
	{
		perror("open");
		return NULL;
	}
	int fd2=open("./1text",O_WRONLY);
	if(fd2<0)
	{
		perror("open");
		return NULL;
	}
	int len=lseek(fd1,0,SEEK_END);
	
	lseek(fd1,len/2,SEEK_SET);
	lseek(fd2,len/2,SEEK_SET);
	char a[128];
	int i;
	int sum=0;
	int res=0;
	while(1)
	{
		res=read(fd1,a,sizeof(a));
		sum=sum+res;
		if(res==0|sum>=(len-(len-len/2)))
		{
			write(fd2,a,res-(sum-len/2));
			break;
		}
		write(fd2,a,res);

	}
	close(fd1);
	close(fd2);

}
int main(int argc, const char *argv[])
{
	
	pthread_t tidf=-1;
	pthread_t tids=-1;
	if(pthread_create(&tidf,NULL,task_one,NULL)!=0)
	{
		printf("error\n");
		return -1;
	}
	if(pthread_create(&tids,NULL,task_two,NULL)!=0)
	{
		printf("error\n");
		return -1;
	}

	pthread_join(tidf,NULL);
	pthread_join(tids,NULL);
	
	return 0;
}

2

#include <myhead.h>
int money=100;
pthread_mutex_t mutex;
void *task(void *arg)
{
	while(1)
	{
		pthread_mutex_lock(&mutex);//上锁
		money=money-10;
		printf("-10还剩:%d\n",money);
		pthread_mutex_unlock(&mutex);//解锁
		sleep(1);
	}
}
int main(int argc, const char *argv[])
{
	pthread_t tid=-1;
	pthread_mutex_init(&mutex,NULL);// 初始化
	if(pthread_create(&tid,NULL,task,NULL)!=0)
	{
		printf("tid error\n");
		return -1;
	}

	while(1)
	{
		pthread_mutex_lock(&mutex);
		money=money-1;
		printf("-1还剩:%d\n",money);
		pthread_mutex_unlock(&mutex);
		sleep(1);
	}

	pthread_join(tid,NULL);
	pthread_mutex_destroy(&mutex);//摧毁锁
	
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值