Is this thread safe? (shared data without mutex/semaphore)
So this is a very particular question:
I use开发者_运维技巧 an embedded system with a single CPU core.
I have one main thread and an interrupt. They share a 32-bit float. The interrupt writes the float, and the main thread reads it. Reads and writes are not synchronized.
The processor documentation states that the 32-bit read is a one-cycle operation.
Am I right in my assessment, that there is no risk that the main thread will read a corrupted value? Or are there other factors?
As long as both reads and writes are atomic operations, it should be fine. How long a read or write takes is immaterial, though it seems likely they are atomic if they are 1 cycle.
Sounds to me like you're safe. If the read is done at once, no one can write to only half of the bytes. Having that said, you do need to make sure the value is always being really read by your thread, instead of being optimized away by the compiler. This might happen if the compiler thinks no one could possible change the variable from the outside. Declaring it as volatile should do the trick (if applicable at all - I'm not familiar with your code).
I think you are fine as long as the interrupt routine does not read the value, and then use the value to compute a new value to write.
Does the documentation also state that a write takes one cycle? If not, then you need protection.
Should be safe - if you suspect it's not, you could disable interrupts before reading the value, then enable after the read. But I'm pretty sure you are fine -
Atomic reads/writes might not be the only consideration in order to make operations thread-safe. I think the answer would depend on the OS memory model as well. You need to make sure that a read in your main thread will get the latest value written by the interrupt.
精彩评论