C++DAY30

 

#include "head.h"
void* callback(void* arg)
{
	int fd, fd1, len;
	pthread_t sid;
	char c=0;
	if ((fd = open("./jpg.jpg", O_RDONLY)) < 0)
	{
		perror("fail to open");
		exit(-1);
	}
 
	if ((fd1 = open("./jpg1.jpg", O_WRONLY|O_CREAT|O_TRUNC, 0666)) < 0)
	{
		perror("fail to open");
		exit(-1);
	}
	len = lseek(fd, 0, SEEK_END);
	len /= 2;
	while(1)
	{
		lseek(fd,0,SEEK_SET);
		lseek(fd1,0,SEEK_SET);
		for(int i=0;i<len;i++)
		{
			read(fd,&c,1);
			write(fd1,&c,1);
		}
		sleep(1);
	}
	pthread_exit(NULL);
	return NULL;
}
int main(int argc, char *argv[])
{
	int fd, fd1, len;
	pthread_t sid;
	char c=0;
	if ((fd = open("./jpg.jpg", O_RDONLY)) < 0)
	{
		perror("fail to open");
		exit(-1);
	}
 
	if ((fd1 = open("./jpg1.jpg", O_WRONLY|O_CREAT|O_TRUNC, 0666)) < 0)
	{
		perror("fail to open");
		exit(-1);
	}
	len = lseek(fd, 0, SEEK_END);
	while(1)
	{
		lseek(fd,0,SEEK_SET);
		lseek(fd1,0,SEEK_SET);
		for(int i=0;i<len;i++)
		{
			read(fd,&c,1);
			write(fd1,&c,1);
		}
		sleep(1);
	}	
	if(pthread_create(&sid,NULL,callback,NULL)!=0)
	{
		fprintf(stderr, "failed __%d__\n",__LINE__);
		return -1;
	}

	pthread_join(sid,NULL);
	return 0;
}

 

#include "head.h"
char buf[]="1234567";
// A线程打印buf字符串的函数
void* printfBuf(void* arg) {
	while (1) 
	{
		// 判断buf是否等于"1234567",如果不等于则等待条件变量发出信号
		while((strcmp(buf, "1234567") != 0)||(strcmp(buf,"7654321") != 0))
		{
			printf("%s\n", buf);//打印字符串
		}
	}
	return NULL;
}
// B线程倒置buf字符串的函数
void* circulate(void* arg) {
	while (1) 
	{
		// 判断buf是否等于"7654321",如果不等于则等待条件变量发出信号
		while((strcmp(buf, "7654321") != 0) || (strcmp(buf,"1234567") != 0))
		{
			int len = strlen(buf);//倒置buf字符串
			for (int i = 0; i < len / 2; i++) 
			{
				char temp = buf[i];
				buf[i] = buf[len - i - 1];
				buf[len - i - 1] = temp;
			};
		}
	}
    return NULL;
}
int main(int argc, const char *argv[])
{
	pthread_t printBuf, reverseBuf;

	// 创建打印线程
	if(pthread_create(&printBuf, NULL, printfBuf, NULL) != 0)
	{
		fprintf(stderr,"printBuf failed __%d__\n",__LINE__);
		return -1;
	}
	// 创建倒置线程
	if(pthread_create(&reverseBuf, NULL, circulate, NULL) != 0)
	{
		fprintf(stderr,"reverseBuf failed __%d__\n",__LINE__);
		return -1;
	}
	// 等待线程结束
	pthread_join(printBuf, NULL);
	pthread_join(reverseBuf, NULL);
	return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值