12.07

1.。

2.

#include "myhead.h"
void *task(void *arg){
	printf("我是分支线程1.tid=%#lx\n",pthread_self());
	int fd1=-1;//创建并打开文件2,
	if((fd1=open("./1text.txt",O_WRONLY|O_CREAT,0664))==-1){
		perror("create 1txt error");
	}
	int fd2=-1;//打开被拷贝文件
	if((fd2=open("./text.txt",O_RDONLY))==-1){
		perror("read error");
	}
	int len=lseek(fd2,0,SEEK_END);//计算文件长度
	lseek(fd2,0,SEEK_SET);//光标定位到开头
	printf("len=%d\n",len);
	char rbuf[128];
	for(int i=0;i<(len/2);i++){//拷贝一半
		read(fd2,rbuf,1);
		write(fd1,rbuf,1);
		write(1,rbuf,1);
	}
	close(fd1);
	close(fd2);
	puts("");
	pthread_exit(NULL);//结束分支线程1
}
void *task1(void *arg){
	printf("我是分支线程2,tid=%#lx\n",pthread_self());
	int fd1=-1;
	if((fd1=open("./1text.txt",O_WRONLY|O_CREAT,0664))==-1){
		perror("create 1txt error");
	}
	int fd2=-1;
	if((fd2=open("./text.txt",O_RDONLY))==-1){
		perror("read error");
	}
	int len=lseek(fd2,0,SEEK_END);
	printf("len=%d\n",len);
	lseek(fd2,(len/2),SEEK_SET);//光标定位到一半的位置
	lseek(fd1,(len/2),SEEK_SET);
	char rbuf[128];
	for(int i=(len/2);i<len;i++){//拷贝另一半
		read(fd2,rbuf,1);
		write(fd1,rbuf,1);
		write(1,rbuf,1);
	}
	puts("");
	close(fd1);
	close(fd2);
	pthread_exit(NULL);
}


int main(int argc, const char *argv[])
{
	pthread_t tid[2]={-1,-1};//创建两个子进程
	if(pthread_create(&tid[0],NULL,task,NULL)!=0){
		printf("task create error\n");
		return -1;
	}
	if(pthread_create(&tid[1],NULL,task1,NULL)!=0){
		printf("task1 cteate error\n");
		return -1;
	}
	printf("我是主线程,线程号为:%#lx",pthread_self());
	int fd=-1;//穿件一个文件,写入东西
	if((fd=open("./text.txt",O_RDWR|O_CREAT|O_TRUNC,0664))==-1){
		perror("create txt error");
		return -1;
	}
	char buf[128]="hello world";
	write(fd,buf,strlen(buf));
	close(fd);
	pthread_join(tid[0],NULL);//回收资源
	pthread_join(tid[1],NULL);

	return 0;
}

3.

#include "myhead.h"
int money=5000;
pthread_mutex_t mutex;
void *task(void *arg){
	while(1){
		pthread_mutex_lock(&mutex);
		money=money-50;
		printf("李四线程取了50元还剩%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 create error");
		return -1;
	}
	while(1){
		pthread_mutex_lock(&mutex);
		money=money-100;
		printf("张三线程取了100元还剩%d元\n",money);
		pthread_mutex_unlock(&mutex);
		sleep(1);
	}
	pthread_join(tid,NULL);
	pthread_mutex_destroy(&mutex);
	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值