Domanda

i use timespec structure in multi-threaded code - one thread calls clock_gettime() to fill in the global timespec structure, the other - reads this structure. Question: is clock_gettime() call atomic or I have to use mutex?

È stato utile?

Soluzione

I would be very surprised if it was, though I can't find any reference on it. Calling clock_gettime is nothing but calling a library function. So if I'm right, you definitely need a mutex to ensure that another thread is not reading the struct timespec while clock_gettime et reading it.

Altri suggerimenti

The clock_gettime man page - http://linux.die.net/man/3/clock_gettime - doesn't say it's atomic so you've no reasonable expectation of it being atomic, and the structure contains two longs so you've no particularly sound basis to even hope. Still, if your hardware supports atomic operations on 64-bit values then rather than fiddle with pointers as Remus suggests, or use a mutex, you could populate another timespec then atomically copy it over your global one, but if your hardware doesn't guarantee memory updates are visible across cores and CPUs (e.g. recent Intel/AMD hardware does, but at least 10 years ago when I cared the UltraSparc's didn't) then you'll need an explicit memory barrier (i.e. some machine code injected into your program - possibly using a compiler- or system-provider "builtin" function) to ensure visibility; a mutex implementation will already handle that for you.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top