Reputation: 97
Can someone clarify to me if the following piece of code is thread safety?
int get_time(uint64_t *time)
{
struct timespec spec;
if (!time)
return -EFAULT;
if (clock_gettime(CLOCK_REALTIME, &spec) == -1)
return -errno;
*time = //convert timespec into nanoseconds
return SUCCESS;
}
This is an API in a library that could be called by multiple threads. The spec is a local variable so it not should be a problem. Correct? My doubt is about the clock_getime (POSIX.1-2001) and the assignment to the time argument. I would to introduce a mutex, but I'm not sure if it is strictly required.
Upvotes: 3
Views: 2245
Reputation: 45654
You aren't using anything but automatic variables in your code, and the only function-call (clock_gettime
) is inherently thread-safe, so the answer is:
Yes, it's safe.
3.396 Thread-Safe
A function that may be safely invoked concurrently by multiple threads. Each function defined in the System Interfaces volume of IEEE Std 1003.1-2001 is thread-safe unless explicitly stated otherwise. Examples are any "pure" function, a function which holds a mutex locked while it is accessing static storage, or objects shared among threads.
There is no exception listed on the spec for that function:
http://pubs.opengroup.org/onlinepubs/009695399/functions/clock_getres.html
Upvotes: 8