IO线程练习

两段代码分别展示了C语言中使用pthread库创建多线程的应用。第一段代码创建一个线程实时显示系统时间,直到用户输入quit退出。第二段代码创建一个线程不断反转字符串,主线程检查字符串是否恢复到初始状态并打印。
摘要由CSDN通过智能技术生成

 1.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include <pthread.h>

void* timesum (void *arg)
{
	time_t t;
	time(&t);
	struct tm *ti=NULL;
	while(1)
	{
		t=time(NULL);
		ti=localtime(&t);
		if(NULL==ti)
		{
			perror("localtime");
			return NULL ;
		}
		printf("%d-%02d-%02d %02d:%02d:%02d\r",\
				ti->tm_year+1900,ti->tm_mon+1,ti->tm_mday,\
				ti->tm_hour,ti->tm_min,ti->tm_sec);
		fflush(stdout);
		sleep(1);
	}

}

int main(int argc, const char *argv[])
{


	pthread_t sid;
	pthread_create(&sid,NULL,timesum,NULL);

	char s[5]="";
	scanf("%s",s);
	while(1) 
	{
		if(strcmp("quit",s)==0)
		{
			break;
		}
	}
	return 0;
}

2. 

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>

char buf[]="1234567";

void *other(void *arg)
{
	char s;
	int l=strlen(buf);
	while(1)
	{
		for(int i=0;i<l/2;i++)
		{
			s=buf[i];
			buf[i]=buf[l-i-1];
			buf[l-i-1]=s;
		}	
	}

}

int main(int argc, const char *argv[])
{
	pthread_t tid;
	pthread_create(&tid,NULL,other,NULL);
	while(1)
	{
		if(buf[0]=='1'&&buf[1]=='2'&buf[2]=='3')
		{
			printf("主:%s\n",buf);
		}
		else if(buf[0]=='7'&&buf[1]=='6'&&buf[2]=='5')
		{
			printf("主:%s\n",buf);
		}else
		{
			continue;
		}
	}
	
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值