Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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? 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.

So it looks like any sufficiently POSIX compliant system should have a thread safe implementation of time.

However, could a POSIX system choose to implement time_t in a matter which actually makes it a pointer and still be compliant? 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? Or is there some requirement or convention for time_t that I'm missing in this aspect?

How would I best go about verifying that time is thread safe on a few UNIX platforms? Particularly, AIX, HP-UX, Linux, and Solaris. Stepping through the disassembly in a debugger could work, but the implementations may change.

like image 525
Kizaru Avatar asked Sep 28 '15 07:09

Kizaru


Video Answer


1 Answers

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.

thread 1                                    thread 2
                                            mov eax, static_internal_value
mov eax, static_internal_value
return 
                                            return
like image 152
mksteve Avatar answered Oct 19 '22 17:10

mksteve