Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is standard C mktime thread safe on linux?

The man page of mktime didn't mention thread safety of mktime, but it did mention this which make it look like thread unsafe:

Calling mktime() also sets the external variable tzname with information about the current time zone.

I know on Linux mktime calls tzset to set tzname, which is a char*[]:

extern char *tzname[2];

and tzset will read environment variable TZ and file /etc/localtime. So unless mktime uses a mutex to protect all these operations, I can't see how it can be thread safe.

like image 398
swang Avatar asked Aug 21 '13 10:08

swang


People also ask

Is Mktime thread-safe?

Threadsafe: Yes. Locale Sensitive: The behavior of this function might be affected by the LC_TOD category of the current locale. The mktime() function converts a stored tm structure (assume to be in job local time) pointed to by time , into a time_t structure suitable for use with other time functions.

Is Strftime thread-safe?

Pointer to a time structure as created by the gmtime or localtime functions. Refer to your platform-specific documentation for details. Under Linux, strftime is not thread-safe.

Is Asctime thread-safe?

Values for the broken-down time structure can be obtained by calling gmtime() or localtime(). The asctime_r() function is thread-safe and shall return values in a user-supplied buffer instead of possibly using a static data area that may be overwritten by each call.


1 Answers

It's true that mktime has a side effect, but the side effect should be harmless in most programs.

According to POSIX, the side effect will be as if tzset has been called, which in turn merely copies the timezone information from the TZ environment variable to the tzname array of C strings. If your application doesn't change TZ, you will have no problem with calling mktime() concurrently.

In addition to this, GNU libc's tzset does use a mutex to protect the integrity of tzname. This is a quality-of-implementation addition not guaranteed by the standard.

like image 167
user4815162342 Avatar answered Oct 11 '22 21:10

user4815162342