Reputation: 7225
I'm working on Linux (CentOS 6.3 distribution with libc-2.12.so).
I wonder if the C library function time()
, localtime()
, mktime()
could be used under multiple thread environment.
Just for an example (not necessarily my project code):
#include <stdio.h>
#include <time.h>
int main()
{
time_t timep;
struct tm *p;
for (int i = 0; i < 1000; ++i)
{
time(&timep);
printf("time() : %d \n", timep);
p = localtime(&timep);
timep = mktime(p);
printf("time()->localtime()->mktime():%d\n", timep);
}
return 0;
}
What if I wrapper the above code with OpenMP? that is to put it under multiple threaded environment.
#include <stdio.h>
#include <time.h>
#include <omp.h>
int main()
{
time_t timep;
struct tm *p;
#pragma omp parallel for
for (int i = 0; i < 1000; ++i)
{
time(&timep);
printf("time() : %d \n", timep);
p = localtime(&timep);
timep = mktime(p);
printf("time()->localtime()->mktime():%d\n", timep);
}
return 0;
}
Upvotes: 1
Views: 3460
Reputation: 158459
localtime
is not thread safe, from the draft C99 standard section 7.23.3
Time conversion functions says:
Except for the strftime function, these functions each return a pointer to one of two types of static objects: a broken-down time structure or an array of char. Execution of any of the functions that return a pointer to one of these object types may overwrite the information in any object of the same type pointed to by the value returned from any previous call to any of them. The implementation shall behave as if no other library functions call these functions.
localtime
comes under section 7.23.3.4
and falls under that condition. The man page for localtime also clearly states it is not thread safe:
The four functions asctime(), ctime(), gmtime() and localtime() return a pointer to static data and hence are not thread-safe. Thread-safe versions asctime_r(), ctime_r(), gmtime_r() and localtime_r() are specified by SUSv2, and available since libc 5.2.5
Neither time
nor mktime
have similar conditions attached to them in the standard.
Upvotes: 2
Reputation: 122383
From manual localtime:
The four functions asctime(), ctime(), gmtime() and localtime() return a pointer to static data and hence are not thread-safe. Thread-safe versions asctime_r(), ctime_r(), gmtime_r() and localtime_r() are specified by SUSv2, and available since libc 5.2.5.
Upvotes: 4