#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 + ;
//注意下面两行的区别
struct tm* ptm = localtime(&tNow);
struct tm* ptmEnd = localtime(&tEnd); char szTmp[] = {};
strftime(szTmp,,"%H:%M:%S",ptm);
char szEnd[] = {};
strftime(szEnd,,"%H:%M:%S",ptmEnd); printf("%s /n",szTmp);
printf("%s /n",szEnd); system("PAUSE");
return EXIT_SUCCESS;
}

最后出来的结果是:

16:49:49
16:49:49

和最初想法不一致。

查阅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。

将location修改为location_r后,输出结果:

16:22:02
16:52:02

localtime是直接返回strcut tm*指针(如果成功的话);这个指针是指向一个静态变量的;因此,返回的指针所指向的静态变量有可能被其他地方调用的localtime改掉,例如多线程使用的时候。

localtime_r则是由调用者在第二个参数传入一个struct tm result指针,该函数会把结果填充到这个传入的指针所指内存里面;成功的返回值指针也就是struct tm result。

其他的时间函数,如asctime,asctime_r;ctime,ctime_r;gmtime,gmtime_r都是类似的,所以,时间函数的 _r 版本都是线程安全的。

最新文章

  1. linux使用wkhtmltopdf报错error while loading shared libraries:
  2. 【转】Linux常用命令大全
  3. tomcat启动时 myeclipse控制台中文乱码
  4. WCF通过SVCUtil.exe生成客户端代理类和配置文件(转)
  5. CentOS 6.5 搭建 LAMP 环境
  6. ASPxCallback控件
  7. Android中Cursor(游标)类的概念和用法
  8. 在ASP.NET MVC 中获取当前URL、controller、action 、参数
  9. 面试总结之mysql
  10. Ajax.Nodejs.跨域访问
  11. 环境变量配置文件,本地登录前提示信息/etc/issue
  12. js用canvans 实现简单的粒子运动
  13. DAY19、日常模块
  14. canvas如何自适应屏幕大小
  15. wifi rate vs mode
  16. 【洛谷】【数论】P1876 开灯
  17. mysql数据库基于LVM快照的备份
  18. IOS11下fixed中input光标错位问题
  19. Android Studio 安装在Windows10中的陷阱
  20. c#开发地磅称重软件

热门文章

  1. 加了moment.js和中文语言包,那么其它时间控件的中文包就可以不引用
  2. asp:ObjectDataSource+asp:GridView 实现真分页
  3. Solr删除managedschema
  4. LVS负载均衡之持久性连接介绍(session篇)
  5. Android----Thread+Handler 线程 消息循环(转载)
  6. C# 使用系统方法发送异步邮件
  7. Snip for Mac(桌面截图工具)安装
  8. .NET压缩图片保存 .NET CORE WebApi Post跨域提交 C# Debug和release判断用法 tofixed方法 四舍五入 (function($){})(jQuery); 使用VUE+iView+.Net Core上传图片
  9. 关于ps cs5的一些问题
  10. sqlserver不太常见的,可能常见但又疑问的tsql语句