+ -
当前位置:首页 → 问答吧 → 浅谈time

浅谈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);

作者: pdsxw123   发布时间: 2010-08-08

本帖最后由 davelv 于 2010-08-10 10:11 编辑

在我这里多线程time()函数没有出现什么问题。楼主不如把自己测试源码贴出来让大家看看
以下是glibc2.12的time()实现
  1. /* Return the time now, and store it in *TIMER if not NULL.  */
  2. time_t
  3. time (timer)
  4.      time_t *timer;
  5. {
  6.   __set_errno (ENOSYS);

  7.   if (timer != NULL)
  8.     *timer = (time_t) -1;
  9.   return (time_t) -1;
  10. }
复制代码
ctime 不是线程安全的,所以有ctime_r作为替代。
  1. /* Return a string as returned by asctime which
  2.    is the representation of *T in that form.  */
  3. char *
  4. ctime (const time_t *t)
  5. {
  6.   /* The C Standard says ctime (t) is equivalent to asctime (localtime (t)).
  7.      In particular, ctime and asctime must yield the same pointer.  */
  8.   return asctime (localtime (t));
  9. }
复制代码
  1. /* Return a string as returned by asctime which is the representation
  2.    of *T in that form.  Reentrant version.  */
  3. char *
  4. ctime_r (const time_t *t, char *buf)
  5. {
  6.   struct tm tm;
  7.   return __asctime_r (__localtime_r (t, &tm), buf);
  8. }
复制代码

作者: davelv   发布时间: 2010-08-10

1.由于在程序中需要使用time函数获取当前时间戳,在多个线程中调用的话,发现有时time(NULL)返回值为0,或者返回一个不正常的时间值。


这个应该不会吧?

作者: shang2010   发布时间: 2010-08-10