简体   繁体   English

即使提供了NULL参数,C标准time()函数线程也是安全的吗?

[英]Is the C standard time() function thread safe even if provided a NULL parameter?

Seems like bit of a silly question but it got me thinking... 看起来有点像一个愚蠢的问题,但它让我思考......

According to here , time is required to be thread safe on a compliant system, correct? 这里time要求是线程安全的柔性系统上,是否正确? This requirement holds regardless of the parameters to the function. 无论函数的参数如何,此要求都成立。 A few functions are listed as not required to be thread safe if provided a NULL argument, and time is not included. 如果提供NULL参数,则列出的一些函数不需要是线程安全的,并且不包括time

So it looks like any sufficiently POSIX compliant system should have a thread safe implementation of time . 所以看起来任何足够的POSIX兼容系统都应该有一个线程安全的time实现。

However, could a POSIX system choose to implement time_t in a matter which actually makes it a pointer and still be compliant? 但是,POSIX系统是否可以选择在实际上使其成为指针但仍然符合要求的情况下实现time_t So if a NULL parameter is provided to store the result, then wouldn't all bets on its thread safety be off as it would likely return a pointer to some static storage? 因此,如果提供一个NULL参数来存储结果,那么它的线程安全上的所有下注都不会被关闭,因为它可能会返回指向某个静态存储的指针吗? Or is there some requirement or convention for time_t that I'm missing in this aspect? 或者是否有一些我在这方面缺少的time_t要求或约定?

How would I best go about verifying that time is thread safe on a few UNIX platforms? 我最好如何在几个UNIX平台上验证time是否是线程安全的? Particularly, AIX , HP-UX , Linux , and Solaris . 特别是AIXHP-UXLinuxSolaris Stepping through the disassembly in a debugger could work, but the implementations may change. 在调试器中单步执行反汇编可能会有效,但实现可能会更改。

Yes it is thread safe. 是的,它是线程安全的。

time_t time( NULL );

If it implemented an internal value, at the point it returned, it would always have to copy from the internal value to the return value (register?). 如果它实现了一个内部值,那么在返回时,它总是必须从内部值复制到返回值(寄存器?)。 That copy would make it thread-safe as it would fit in all modern processors single copy. 该副本将使其成为线程安全的,因为它适用于所有现代处理器单一副本。

mov eax, static_internal_value
return

Imagine that wasn't the case, and 2 threads came in. They would both copy out the same value - again, can't see how this could be incorrect. 想象事实并非如此,并且有2个线程进来。他们都会复制出相同的值 - 再次,看不出这是不正确的。

thread 1                                    thread 2
                                            mov eax, static_internal_value
mov eax, static_internal_value
return 
                                            return

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM