localtime与localtime_r

来源:互联网 发布:全国省市县数据库 sql 编辑:程序博客网 时间:2024/05/18 00:02

localtime与localtime_r

代码:

#include <stdio.h>#include <stdlib.h>#include <time.h>#include <iostream>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);    struct tm ptm_r;    struct tm ptmEnd_r;    localtime_r(&tNow, &ptm_r);    localtime_r(&tEnd, &ptmEnd_r);    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);    strftime(szTmp,50,"%H:%M:%S",&ptm_r);    strftime(szEnd,50,"%H:%M:%S",&ptmEnd_r);    printf("%s \n",szTmp);    printf("%s \n",szEnd);    return 1;}

运行结果如下:

22:16:03 22:16:03 21:46:03 22:16:03 

函数说明:

  • struct tm *localtime(const time_t *timep);
  • struct tm *localtime_r(const time_t *timep, struct tm *result);

  • localtime是直接返回strcut tm*指针;这个指针是指向一个静态变量的;实际的内存是localtime内部通过static申请的静态内存。因此,返回的指针所指向的静态变量有可能被其他地方调用的localtime改掉,例如多线程使用的时候。所以通过localtime调用后的返回值不及时使用的话,很有可能被其他线程localtime调用所覆盖掉;
    localtime只会保留最后一份数据,如果在多线程中使用,会存在覆盖的问题,不是线程安全的。

  • localtime_r则是由调用者在第二个参数传入一个struct tm result指针,该函数会把结果填充到这个传入的指针所指内存里面;多线程应用里面,应该用localtime_r函数替代localtime函数,因为localtime_r是线程安全的。
    其他的时间函数,如asctime,asctime_r;ctime,ctime_r;gmtime,gmtime_r都是类似的,所以,时间函数的 _r 版本都是线程安全的。

原创粉丝点击