2/28作业

1.标准IO函数时候讲解的时钟代码,要求输入quit字符串后,结束进程

#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <time.h>
#include <string.h>
void* callback(void* arg)
{
	time_t t;
	int line=0;
	while(1)
	{
		line++;
		t = time(NULL);
		struct tm* info = localtime(&t);
		printf("[%d] %4d-%02d-%02d %02d:%02d:%02d\n",\
				line,\
				info->tm_year+1900,info->tm_mon+1,info->tm_mday,\
				info->tm_hour,info->tm_min,info->tm_sec);
		sleep(2);
	}
}
int main(int argc, const char *argv[])
{
	pthread_t tid;
	if(pthread_create(&tid,NULL,callback,NULL)!=0)
	{
		fprintf(stderr,"error\n");
		return -1;
	}
	char str[20]="";
	while(1)
	{
		scanf("%s",str);
		if(strcmp(str,"quit")==0)
		{
			break;
		}
	}
	return 0;
}

 

2.要求定义一个全局变量 char buf[] = "1234567",创建两个线程,不考虑退出条件。

a.A线程循环打印buf字符串,

b.B线程循环倒置buf字符串,即buf中本来存储1234567,倒置后buf中存储7654321. 不打印!!

c.倒置不允许使用辅助数组。

d.要求A线程打印出来的结果只能为 1234567 或者 7654321

e.不允许使用sleep函数

#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
char str[]="1234567";
int flag=0;
void* callback1(void* arg)
{
	while(1)
	{
		if(1==flag)
		{
			printf("%s\n",str);
			flag=0;
		}
	}
	pthread_exit(NULL);
}
void* callback2(void* arg)
{
	int len = strlen(str);
	char temp=0;
	while(1)
	{
		if(0==flag)
		{
			for(int i=0;i<len/2;i++)
			{
				temp=str[i];
				str[i]=str[len-1-i];
				str[len-1-i]=temp;
			}
			flag=1;
		}
	}
	pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
	pthread_t tid1;
	if(pthread_create(&tid1,NULL,callback1,NULL)!=0)
	{
		fprintf(stderr,"error\n");
		return -1;
	}
	pthread_t tid2;
	if(pthread_create(&tid2,NULL,callback2,NULL)!=0)
	{
		fprintf(stderr,"error\n");
		return -1;
	}
	while(1)
	{
	}
	pthread_join(tid1, NULL);
	pthread_join(tid2, NULL);

	return 0;
}

猜你喜欢

转载自blog.csdn.net/k_weihgl/article/details/129267427
今日推荐