开发者

Is reading a double an atomic operation in linux?

I'm creating a simple server which stores several variables globally. On occasion these variables will update and during this time the variables are locked from other threads. Each client who accesses the server is granted their own thread, but has no way to change these variables and are essentially readonly. My question to the internet is do I need to 开发者_如何学JAVAworry about either a) two threads reading the same variable at the same time (not changing) or b) the writing the variable process interrupting the reading process.

I know that in most cases writing a double is not an atomic operation because it is usually more than one register, but can the reading operation be interrupted?

Thanks


My first guess is that this has nothing to do with Linux as an OS.

It is for sure related to the CPU in use, as some may be able to load/store double in memory in 1 operation. The x86 series has such an op-code for the FPU.

It may also be linked to the compiler that can make use of these CPU abilities to load/store doubles in 1 operation. Don't know what gcc does.


[Edit] Apologies, I was out of it when I read this question originally and gave an incorrect answer which jalf kindly pointed out.

I know that in most cases writing a double is not an atomic operation because it is usually more than one register, but can the reading operation be interrupted?

Yes. Imagine trying to write your own IEEE double-precision floating type using two WORD-sized variables. We cannot read both of these atomically, as they are two distinct parts. One could be in the process of being modified concurrently at the same time we are trying to read.

do I need to worry about either a) two threads reading the same variable at the same time (not changing) or b) the writing the variable process interrupting the reading process.

a: no

b: yes

You'll either need to use a synchronization mechanism for the readers (in addition to the writer) or, if you're like me, just make it a WORD-sized single-precision float for the shared data which is often atomic for reading on modern systems (though you should verify this), stick to atomic operations to modify it, and avoid the headaches.


If you are only reading, you should not have to worry about atomicity. If you are reading and writing, you will need to use a mutex lock, both on your "server" and "client" thread. Locking only when writing only gets half of the job done.

Now, with a single double you may be in some luck depending on your compiler works and on your exact hardware architecture. See this answer.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜