[英]is clock_gettime() call atomic?
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. 我在多线程代码中使用timespec结构-一个线程调用
clock_gettime()
来填充全局timespec结构,另一个线程读取该结构。 Question: is clock_gettime()
call atomic or I have to use mutex? 问题:
clock_gettime()
是原子调用还是我必须使用互斥锁?
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. 调用
clock_gettime
只是调用库函数。 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. 因此,如果我是对的,那么您肯定需要一个互斥体,以确保在
clock_gettime
等读取时,另一个线程不会读取struct timespec
。
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 long
s so you've no particularly sound basis to even hope. 该
clock_gettime
手册页- http://linux.die.net/man/3/clock_gettime -不说这是原子,所以你就把它是原子的没有合理的预期,以及结构包含两个long
这么你已经没有特别可靠的基础甚至没有希望。 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 (eg 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 (ie some machine code injected into your program - possibly using a compiler- or system-provider "builtin" function) to ensure visibility; 但是,如果您的硬件支持对64位值进行原子操作,而不是像Remus所建议的那样摆弄指针,或者使用互斥锁,则可以填充另一个时间
timespec
然后以原子方式将其复制到全局时间timespec
,但是如果您的硬件不能保证内存更新在内核和CPU上可见(例如,最新的Intel / AMD硬件可以看到,但是至少在10年前,当我关心UltraSparc的时候不知道),那么您将需要显式的内存屏障(即,将一些机器代码注入程序中) -可能使用编译器或系统提供者的“内置”功能)以确保可见性; a mutex implementation will already handle that for you. 互斥体实现将已经为您处理了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.