0

I'm writing some multithreaded C code, and I just came across this StackOverflow question. It sounds like the compiler will make sure that I/O to different parts of a struct will never intersect or cause some sort of race condition.

My question, as an extension, is that are there similar guarantees for two different structs that are spatially close in shared memory?

Edit: Spatially close as in "same page". Would two writes from two different threads to the same page cause a race condition? One guy could end up flusing a stale page from his cache to memory (is this possible?).

Let's say I have two bits, as their own structs, in shared memory. If they end up being adjacent, can one thread writing to one of them overwrite the other? Would I have to serialize all threads with one lock for access to any of these structs in shared memory?

Or is all of this, and the issue in the referenced question, a risk anyway in C99?

WestaAlger
  • 501
  • 3
  • 12
  • Yes. If you're writing to adjacent bits within the same unit, that's a race. The write would be done by bitmasking on the surrounding char/short/int/long--you'd be essentially racing for the same spot in memory. – Petr Skocik Jun 07 '19 at 20:18
  • 1
    "If they end up being adjacent" - well that seems like a false premise, given the assumption that both bits are part of different structs – harold Jun 07 '19 at 20:20
  • @harold Sounds right. I completely forgot about structure alignment in C. So no read/write should intersect between different structs. Would it matter if the structs ended up on the same page? Edited question to clarify. – WestaAlger Jun 07 '19 at 20:52
  • 1
    There is no such thing as a "flush" of a page to RAM. – curiousguy Jun 08 '19 at 02:57

0 Answers0