Quantcast
Viewing all articles
Browse latest Browse all 10

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.


    Image may be NSFW.
    Clik here to view.
    Image may be NSFW.
    Clik here to view.

    Viewing all articles
    Browse latest Browse all 10

    Trending Articles