localtime and Localtime_r
Code:
#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:
22:16:03
22:16:03
21:46:03
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.