localtime 和 localtime_r

上程序:

[c-sharp] view plain copy print ?
  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.     time_t tNow =time(NULL); 
  10.     time_t tEnd = tNow + 1800; 
  11.     //注意下面两行的区别 
  12.     struct tm* ptm = localtime(&tNow); 
  13.     struct tm* ptmEnd = localtime(&tEnd);
  14.  
  15.     char szTmp[50] = {0}; 
  16.     strftime(szTmp,50,"%H:%M:%S",ptm); 
  17.     char szEnd[50] = {0}; 
  18.     strftime(szEnd,50,"%H:%M:%S",ptmEnd); 
  19.      
  20.  
  21.     printf("%s /n",szTmp); 
  22.     printf("%s /n",szEnd); 
  23.      
  24.  
  25.     system("PAUSE"); 
  26.     return EXIT_SUCCESS; 

最后出来的结果是:

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。

修改程序:

[c-sharp] view plain copy print ?
  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.     time_t tNow =time(NULL); 
  10.     time_t tEnd = tNow + 1800; 
  11.  
  12.     //在这里修改程序 
  13.     //struct tm* ptm = localtime(&tNow); 
  14.     //struct tm* ptmEnd = localtime(&tEnd); 
  15.     struct tm ptm = { 0 }; 
  16.     struct tm ptmEnd = { 0 }; 
  17.     localtime_r(&tNow, &ptm); 
  18.     localtime_r(&tEnd, &ptmEnd); 
  19.      
  20.     char szTmp[50] = {0}; 
  21.     strftime(szTmp,50,"%H:%M:%S",&ptm); 
  22.     char szEnd[50] = {0}; 
  23.     strftime(szEnd,50,"%H:%M:%S",&ptmEnd); 
  24.     printf("%s /n",szTmp); 
  25.     printf("%s /n",szEnd); 
  26.      
  27.  
  28.     system("PAUSE"); 
  29.     return EXIT_SUCCESS; 

最后出来的结果是:

10:29:06
10:59:06

 

另外:

跨平台的线程安全的localtime和gmtime


localtime()返回一个内部静态变量指针,是线程不安全的。
localtime_r()是线程安全的版本,可是Windows上没有。

boost::date_time::c_time为localtime和gmtime这些ctime函数提供了一个统一的版本.
定义为c_time中的2个静态成员函数。

头文件:c_time.hpp
命名空间:boost::date_time

struct c_time {
    static tm* localtime(const time_t* t, tm* result);
    static tm* gmtime(const time_t* t, tm* result);
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值