2022.10.12work

1. 修改标准IO时候写的时钟代码,要求输入'q'后,能够退出该程序。

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <pthread.h>
#include <errno.h>

void *pthrcell(void *arg)
{
	FILE *fp=fopen("time.txt","a+");
	int num=1,a;
	while((a=fgetc(fp))!=-1){
		if(a=='\n'){
			num++;
		}
	}
	while(1){
		size_t t=time(NULL);
		struct tm *ct=localtime(&t);
		fprintf(fp,"[%d] %02d-%02d-%02d %02d:%02d:%02d\n",
				num,\
				ct->tm_year+1900,\
				ct->tm_mon+1,\
				ct->tm_mday,\
				ct->tm_hour,\
				ct->tm_min,\
				ct->tm_sec);
		fflush(fp);
		num++;
		sleep(1);
	}
	fclose(fp);
	return 0;

}

int main(int argc, const char *argv[])
{
	pthread_t tpid;
	if(pthread_create(&tpid,NULL,pthrcell,NULL)){
		perror("pthread_cread:");
		return 0;
	}
	char c=0;
	while(1){
		c=fgetc(stdin);
		if(c=='q'){
			break;
		}
	}
	return 0;
}

 

2. 要求创建两个线程,以及一个全局变量,char str[] = "123456"

要求如下:

1)一个线程专门用于打印str;

2)另外一个线程专门用于倒置str字符串,不使用辅助数组。

3)要求打印出来的结果必须是123456或者654321,不能出现乱序情况

 

#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <errno.h>

char str[]="123456";

void *pth1cell(void *arg)   // 打印子线程
{
	while(1){
		printf("%s\n",str);
		sleep(1);
	}
}

void *pth2cell(void *arg)   // 翻转子线程
{
	long long rev=0x676767676767;    // 0x67='1'+'6'
	long long *aid=(long long *)str;
	while(1){
		*aid=rev-*aid;
		sleep(1);
	}
}

int main(int argc, const char *argv[])
{
	pthread_t tpid1,tpid2;
	if(pthread_create(&tpid1,NULL,pth1cell,NULL)){
		perror("tpid1:");
		return 0;
	}
	if(pthread_create(&tpid2,NULL,pth2cell,NULL)){
		perror("tpid2:");
		return 0;
	}
	while(1);
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值