+ -
当前位置:首页 → 问答吧 → 被 gettimeofday害死,又一个线程不安全函数,有没有线程安全代替品?

被 gettimeofday害死,又一个线程不安全函数,有没有线程安全代替品?

时间:2010-04-14

来源:互联网

有得想法绕过去,不知道 time安全不,多线程陷阱太多了
小小吐槽一下~

作者: ydfgic   发布时间: 2010-04-14

没有说gettimeofday不是线程安全呀,你怎么用的?

作者: hellioncu   发布时间: 2010-04-14

gettimeofday_r

作者: 专操五毛   发布时间: 2010-04-14

应该是线程安全的吧
http://publib.boulder.ibm.com/in ... ic=/apis/gettod.htm

作者: rain_fish   发布时间: 2010-04-14

回复 1# ydfgic


   透漏下嘛~
第一次听说这个不是线程安全的。。

作者: seer671   发布时间: 2010-04-14

牛人啊,能把一个系统调用变成线程不安全的。

作者: pagx   发布时间: 2010-04-14

以为没有人回复呢~

我开了50个线程在 centos上循环跑,偶尔会出现得到的tv_sec 大4500多秒。
于是我使用 time(0)来代替,也会出现这样的情况

    struct timeval now;
    int ret = gettimeofday(&now, NULL);

    time_t s = ::time(0);
    assert(ret == 0);
    assert (now.tv_sec <= s );
assert 失败,结果会大 4500s。

google 关键词“gettimeofday线程安全”,有一篇
《mktime,localtime_r,gettimeofday是线程安全的吗?》
http://hi.baidu.com/pkuyikai/blo ... bfd23e0cd7da86.html

google “gettimeofday thread-safe”,这篇比较靠前,也有人引用
http://osdir.com/ml/lib.common-c++.bugs/2004-05/msg00007.html

“The problem, according to POSIX documentation, is that time(), and
> therefore gettimeofday(), keeps some static data that is overwritten by
> each call to the function”

作者: ydfgic   发布时间: 2010-04-15

回复 6# pagx

系统调用gettimeofday 是线程安全,这个是c库里的函数啊,虽然没有看c库源码,但是我确实试出来了不一致

作者: ydfgic   发布时间: 2010-04-15