zoukankan      html  css  js  c++  java
  • localtime 和 localtime_r

    ---恢复内容开始---

    上程序:

    1. #include <cstdlib>  
    2. #include <iostream>  
    3. #include <time.h>  
    4. #include <stdio.h>   
    5.   
    6. using namespace std;  
    7.   
    8. int main(int argc, char *argv[])  
    9. {  
    10.     time_t tNow =time(NULL);  
    11.     time_t tEnd = tNow + 1800;  
    12.     //注意下面两行的区别   
    13.     struct tm* ptm = localtime(&tNow);  
    14.     struct tm* ptmEnd = localtime(&tEnd);  
    15.   
    16.     char szTmp[50] = {0};  
    17.     strftime(szTmp,50,"%H:%M:%S",ptm);  
    18.     char szEnd[50] = {0};  
    19.     strftime(szEnd,50,"%H:%M:%S",ptmEnd);  
    20.       
    21.   
    22.     printf("%s /n",szTmp);  
    23.     printf("%s /n",szEnd);  
    24.       
    25.   
    26.     system("PAUSE");  
    27.     return EXIT_SUCCESS;  
    28. }  

    最后出来的结果是:

    21:18:39

    21:18:39

    和最初想法不一致。

    查阅localtime的文档,发现这段话:

    This structure is statically allocated and shared by the functions gmtime and localtime. Each time either one of these functions is called the content of this structure is overwritten.

    也就是说每次只能同时使用localtime()函数一次,要不就会被重写!

    The localtime() function need not be reentrant. A function that is not required to be reentrant is not required to be thread-safe.

    因此localtime()不是可重入的。同时libc里提供了一个可重入版的函数localtime_r();

    Unlike localtime(), the reentrant version is not required to set tzname。

    修改程序:

    1. #include <cstdlib>  
    2. #include <iostream>  
    3. #include <time.h>  
    4. #include <stdio.h>   
    5.   
    6. using namespace std;  
    7.   
    8. int main(int argc, char *argv[])  
    9. {  
    10.     time_t tNow =time(NULL);  
    11.     time_t tEnd = tNow + 1800;  
    12.   
    13.     //在这里修改程序   
    14.     //struct tm* ptm = localtime(&tNow);   
    15.     //struct tm* ptmEnd = localtime(&tEnd);   
    16.     struct tm ptm = { 0 };  
    17.     struct tm ptmEnd = { 0 };  
    18.     localtime_r(&tNow, &ptm);  
    19.     localtime_r(&tEnd, &ptmEnd);  
    20.       
    21.     char szTmp[50] = {0};  
    22.     strftime(szTmp,50,"%H:%M:%S",&ptm);  
    23.     char szEnd[50] = {0};  
    24.     strftime(szEnd,50,"%H:%M:%S",&ptmEnd);  
    25.     printf("%s /n",szTmp);  
    26.     printf("%s /n",szEnd);  
    27.       
    28.   
    29.     system("PAUSE");  
    30.     return EXIT_SUCCESS;  
    31. }  

    最后出来的结果是:

    10:29:06
    10:59:06

    http://blog.csdn.net/maocl1983/article/details/6221810

    ---恢复内容结束---

  • 相关阅读:
    nginx http和https共存
    jQuery prop方法替代attr方法
    idea内置tomcat中java代码热更新
    Linux磁盘空间查看、磁盘被未知资源耗尽
    Mysql order by与limit混用陷阱
    IIS 架构解析
    asp.net MVC 应用程序的生命周期
    Linq专题之var关键字
    ThoughtWorks 2016年第1期DNA活动总结
    对象的深拷贝--反射
  • 原文地址:https://www.cnblogs.com/pengkunfan/p/3794662.html
Copyright © 2011-2022 走看看