struct tm *localtime(const time_t *clock);
这个函数在返回的时候,返回的是一个指针,实际的内存是localtime内部通过static申请的静态内存,所以通过localtime调用后的返回值不及时使用的话,很有可能被其他线程localtime调用所覆盖掉
多线程应用里面,应该用localtime_r函数替代localtime函数,因为localtime_r是线程安全的。
struct tm* localtime_r( const time_t* timer, struct tm* result );
下面这段程序输出结果:
21:18:39
21:18:39
说明,localtime只会保留最后一份数据,如果在多线程中使用,会存在覆盖的问题,不是线程安全的
#include <cstdlib>
#include <iostream>
#include <time.h>
#include <stdio.h>
using namespace std;
int main(int argc, char *argv[])
{
time_t tNow =time(NULL);
time_t tEnd = tNow + 1800;
//注意下面两行的区别
struct tm* ptm = localtime(&tNow);
struct tm* ptmEnd = localtime(&tEnd);
char szTmp[50] = {0};
strftime(szTmp,50,"%H:%M:%S",ptm);
char szEnd[50] = {0};
strftime(szEnd,50,"%H:%M:%S",ptmEnd);
printf("%s /n",szTmp);
printf("%s /n",szEnd);
system("PAUSE");
return EXIT_SUCCESS;
}