localtime is not thread safe


Thats right, current glibc’s implementation of localtime function is not thread-safe, instead we have localtime_r available which offers the same functionality but it is reentrant.
Here is why

  • glibc/time/localtime.c
  • struct tm _tmbuf;
    /* Return the `struct tm' representation of *T in local time,
       using *TP to store the result.  */
    struct tm *
    __localtime_r (t, tp)
         const time_t *t;
         struct tm *tp;
    {
      return __tz_convert (t, 1, tp);
    }
    weak_alias (__localtime_r, localtime_r)
    
    /* Return the `struct tm' representation of *T in local time.  */
    struct tm *
    localtime (t)
         const time_t *t;
    {
      return __tz_convert (t, 1, &_tmbuf);
    }
    libc_hidden_def (localtime)
    

    The localtime representation is returned in a chunk of memory than in the case of localtime_r is given by the user but in the case of the standard localtime every call returns the result in the same memory chunk, currently it uses the file scoped variable _tmbuf in localtime compilation unit.
    So simultaneous calls to the localtime will produce non-desired results in every real concurrency scenario.

    Leave a Reply

    Fill in your details below or click an icon to log in:

    WordPress.com Logo

    You are commenting using your WordPress.com account. Log Out /  Change )

    Google+ photo

    You are commenting using your Google+ account. Log Out /  Change )

    Twitter picture

    You are commenting using your Twitter account. Log Out /  Change )

    Facebook photo

    You are commenting using your Facebook account. Log Out /  Change )

    w

    Connecting to %s

    %d bloggers like this: