localtime在多线程中的问题

2023-08-09 16:18:59 浏览数 (2)

碰到一个奇怪的问题,通过localtime生成本地日期时间打日志,结果日志会出现非北京时间,好奇去查了一个,结果发现此函数是非线程安全函数,原来代码如下:

代码语言:javascript复制
int32_t utc2datetime(uint32_t utctime, SVC_TIME* out_pTime)
{
	time_t rawtime;
	struct tm * p;
	rawtime = utctime;
	p = localtime(&rawtime);
	out_pTime->unYear = (uint32_t)(1900   p->tm_year);
	out_pTime->unMonth = (uint16_t)(1   p->tm_mon);
	out_pTime->unDay = (uint16_t)p->tm_mday;
	out_pTime->unHour = (uint16_t)p->tm_hour;
	out_pTime->unMinute = (uint16_t)p->tm_min;
	out_pTime->unSecond = (uint16_t)p->tm_sec;
	out_pTime->unWeek = (uint16_t)p->tm_wday;
	return 0;
}

localtime,用来获取系统时间,原型在time.h头文件中,定义如下:

代码语言:javascript复制
struct tm *localtime(const time_t *timep);

在实际应用中,用了2个线程一个统计,一个日志使用此函数,结果就会出现读出的SVC_TIME有的是北京时间,有的是-8小时的时间,需要使用线程安全函数,localtime_r和localtime_s,localtime_r是linux下线程安全函数,localtime_s是windows下线程安全函数,定义分别如下:

代码语言:javascript复制
struct tm *localtime_r( const time_t *timer, struct tm *_tm );

errno_t localtime_s(struct tm* _tm,const time_t *time);

注意:localtime_r和localtime_s的参数是相反的

改动原来的函数如下就可以正常使用了:

代码语言:javascript复制
int32_t utc2datetime(uint32_t utctime, SVC_TIME* out_pTime)
{
	time_t rawtime;
	struct tm  tm = {0};
	rawtime = utctime;
#if defined(_WIN32) || defined(_WIN64)
	localtime_s(&tm, &rawtime);
#else
	localtime_r(&rawtime, &tm);
#endif
	out_pTime->unYear = (uint32_t)(1900   tm.tm_year);
	out_pTime->unMonth = (uint16_t)(1   tm.tm_mon);
	out_pTime->unDay = (uint16_t)tm.tm_mday;
	out_pTime->unHour = (uint16_t)tm.tm_hour;
	out_pTime->unMinute = (uint16_t)tm.tm_min;
	out_pTime->unSecond = (uint16_t)tm.tm_sec;
	out_pTime->unWeek = (uint16_t)tm.tm_wday;
	return 0;
}

0 人点赞