LocalTime and Localtime_r

Source: Internet
Author: User
Tags printf
localtime and Localtime_r


#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <iostream>

using namespace std;

int main (int argc, char **argv)
    time_t tnow =time (NULL);
    time_t tEnd = tnow + 1800;
    struct tm* ptm = localtime (&tnow);
    struct tm* ptmend = localtime (&tend);

    struct TM Ptm_r;
    struct TM Ptmend_r;
    Localtime_r (&tnow, &ptm_r);
    Localtime_r (&tend, &ptmend_r);

    Char sztmp[50] = {0};
    Strftime (sztmp,50, "%h:%m:%s", PTM);
    Char szend[50] = {0};
    Strftime (szend,50, "%h:%m:%s", ptmend);

    printf ("%s \ n", sztmp);
    printf ("%s \ n", szend);

    Strftime (sztmp,50, "%h:%m:%s", &ptm_r);
    Strftime (szend,50, "%h:%m:%s", &ptmend_r);
    printf ("%s \ n", sztmp);
    printf ("%s \ n", szend);

    return 1;

The results of the operation are as follows:


Function Description: struct TM *localtime (const time_t *TIMEP);

struct TM *localtime_r (const time_t *TIMEP, struct TM *result);

LocalTime is the direct return strcut tm* pointer, which is a pointer to a static variable, and the actual memory is the static memory that is applied internally by static localtime. As a result, the static variables that the returned pointer points to can be localtime by other local calls, such as when multithreading is used. Therefore, the return value after the localtime call is not used in time, it is likely to be overwritten by other thread localtime calls;
LocalTime only retains the last copy of the data, and if used in multi-threading, there is an overlay problem, not thread-safe.

Localtime_r is a struct TM result pointer passed in the second argument by the caller, which fills the result into the memory of the incoming pointer; in multithreaded applications, the Localtime_r function should be substituted for the localtime function. Because Localtime_r is thread-safe.
Other time functions, such as Asctime,asctime_r;ctime,ctime_r;gmtime,gmtime_r, are similar, so the _r version of the time function is thread-safe.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.