Hi all, so I have a boolean type in C++ on a multiprocessor machine. The variable starts out life as true, and then there are a few threads, any one or more of which might write it to be false.
At the same time, these threads may also read this variable to check its state. I don't care if reading this variable is synchronized with any of the writes, they each happen at different places in the code, and it doesn't matter if it comes before or after any particular write. Now, do I need a lock for this boolean?
The only way I would need a lock is if at the very low level, memory can get corrupted by two competing writes. If, for example, an assembly instruction on processor A is writing 0 to the byte that represents the boolean at the same time as processor B is doing the same... and instead of having written 0, the memory ends up with value 22 or something. That could mess something up.
So, generally, if proc A is writing 3 to a memory location, while proc B is writing 7, with no synchronization, am I guaranteed to end up with at least either 3 or 7? Or is it that easy to break memory?
Edit:
Thanks for the comments guys. Some more info: There is synchronization in the program of course. To summarize, the flag in question is telling if a certain memory pool is "dirty" (needs to be compacted). Any thread can hence decide to set this flag to false (meaning pool is dirty). For example, freeing memory from the pool makes it dirty. Any thread can then also read this flag and set another flag to signal that a clean-up is needed -- this check is done when memory is allocated from the pool, the clean-up is signaled if we're low on memory. Somewhere in my master critical section between iterations, where each thread goes to look for more data to process, I will have the threads check this second flag, and do something appropriate to make sure that: all other theads finish their current iteration, one thread cleans up the memory, sets the first flag back to true (as in pool is not dirty), sets the second flag back to false, and then releases all the threads again.
So I don't think I need a lock because: a lock would ensure that a write doesn't happen at the same time as another write or a read. But who cares, as long as the hardware doesn't fail me, the worst-case-scenario is that the read happens randomly before or after the write -- this is the same thing that would happen if I protected it with a lock, just then we'd really be sure it came before or after...
I think the same argument applies to the second flag I mentioned above.