浅谈time
时间:2010-08-08
来源:互联网
刚看到一贴,讨论时间函数多线程访问安全问题。小弟也发上一贴,讨论下最近一个项目中使用时间函数碰到的问题。
1.由于在程序中需要使用time函数获取当前时间戳,在多个线程中调用的话,发现有时time(NULL)返回值为0,或者返回一个不正常的时间值。
2.在多线程中调用localtime,strftime函数格式化时间,长时间运行,没有问题。localtime在多线程下使用应该是安全的。
没有找到time_t time(time_t* __time_t) 的实现,这个函数在多线程中应该不是安全的,需要的话请采用
//加锁
time_t tt = time(NULL);
1.由于在程序中需要使用time函数获取当前时间戳,在多个线程中调用的话,发现有时time(NULL)返回值为0,或者返回一个不正常的时间值。
2.在多线程中调用localtime,strftime函数格式化时间,长时间运行,没有问题。localtime在多线程下使用应该是安全的。
没有找到time_t time(time_t* __time_t) 的实现,这个函数在多线程中应该不是安全的,需要的话请采用
//加锁
time_t tt = time(NULL);
作者: pdsxw123 发布时间: 2010-08-08
本帖最后由 davelv 于 2010-08-10 10:11 编辑
在我这里多线程time()函数没有出现什么问题。楼主不如把自己测试源码贴出来让大家看看
以下是glibc2.12的time()实现
复制代码
ctime 不是线程安全的,所以有ctime_r作为替代。
复制代码
复制代码
在我这里多线程time()函数没有出现什么问题。楼主不如把自己测试源码贴出来让大家看看
以下是glibc2.12的time()实现
- /* Return the time now, and store it in *TIMER if not NULL. */
- time_t
- time (timer)
- time_t *timer;
- {
- __set_errno (ENOSYS);
-
- if (timer != NULL)
- *timer = (time_t) -1;
- return (time_t) -1;
- }
- /* Return a string as returned by asctime which
- is the representation of *T in that form. */
- char *
- ctime (const time_t *t)
- {
- /* The C Standard says ctime (t) is equivalent to asctime (localtime (t)).
- In particular, ctime and asctime must yield the same pointer. */
- return asctime (localtime (t));
- }
- /* Return a string as returned by asctime which is the representation
- of *T in that form. Reentrant version. */
- char *
- ctime_r (const time_t *t, char *buf)
- {
- struct tm tm;
- return __asctime_r (__localtime_r (t, &tm), buf);
- }
作者: davelv 发布时间: 2010-08-10
1.由于在程序中需要使用time函数获取当前时间戳,在多个线程中调用的话,发现有时time(NULL)返回值为0,或者返回一个不正常的时间值。
这个应该不会吧?
这个应该不会吧?
作者: shang2010 发布时间: 2010-08-10
相关阅读 更多
热门阅读
-
office 2019专业增强版最新2021版激活秘钥/序列号/激活码推荐 附激活工具
阅读:74
-
如何安装mysql8.0
阅读:31
-
Word快速设置标题样式步骤详解
阅读:28
-
20+道必知必会的Vue面试题(附答案解析)
阅读:37
-
HTML如何制作表单
阅读:22
-
百词斩可以改天数吗?当然可以,4个步骤轻松修改天数!
阅读:31
-
ET文件格式和XLS格式文件之间如何转化?
阅读:24
-
react和vue的区别及优缺点是什么
阅读:121
-
支付宝人脸识别如何关闭?
阅读:21
-
腾讯微云怎么修改照片或视频备份路径?
阅读:28