Re: thread-safety: gmtime_r(), localtime_r()

From: Thomas Munro <thomas(dot)munro(at)gmail(dot)com>
To: Peter Eisentraut <peter(at)eisentraut(dot)org>
Cc: Heikki Linnakangas <hlinnaka(at)iki(dot)fi>, pgsql-hackers <pgsql-hackers(at)postgresql(dot)org>
Subject: Re: thread-safety: gmtime_r(), localtime_r()
Date: 2024-08-16 13:09:07
Message-ID: CA+hUKGJirRipOzR4GMrdjwvV-s7QGmgS+HFxpvA=i93G1N3fPg@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

On Tue, Jul 23, 2024 at 10:52 PM Peter Eisentraut <peter(at)eisentraut(dot)org> wrote:
> Let's look at what this code actually does. It just takes the current
> time and then loops through all possible weekdays and months to collect
> and cache the localized names. The current time or time zone doesn't
> actually matter for this, we just need to fill in the struct tm a bit
> for strftime() to be happy. We could probably replace this with
> gmtime() to avoid the question about time zone state. (We probably
> don't even need to call time() beforehand, we could just use time zero.
> But the comment says "We use times close to current time as data for
> strftime().", which is probably prudent.) (Since we are caching the
> results for the session, we're already not dealing with the hilarious
> hypothetical situation where the weekday and month names depend on the
> actual time, in case that is a concern.)

I think you could even just use a struct tm filled in with an example
date? Hmm, but it's annoying to choose one, and annoying that POSIX
says there may be other members of the struct, so yeah, I think
gmtime_r(0, tm) makes sense. It can't be that important, because we
aren't even using dates consistent with tm_wday, so we're assuming
that strftime("%a") only looks at tm_wday.

This change complements CF #5170's change strftime()->strftime_l(), to
make the function fully thread-safe.

Someone could also rewrite it to call
nl_langinfo_l({ABDAY,ABMON,DAY,MON}_1 + n, locale) directly, or
GetLocaleInfoEx(locale_name,
LOCALE_S{ABBREVDAY,ABBREVMONTH,DAY,MONTH}NAME1 + n, ...) on Window,
but that'd be more code churn.

In response to

Responses

Browse pgsql-hackers by date

  From Date Subject
Next Message Thomas Munro 2024-08-16 13:12:43 Re: thread-safety: gmtime_r(), localtime_r()
Previous Message Robert Haas 2024-08-16 12:55:03 Re: Add new protocol message to change GUCs for usage with future protocol-only GUCs