问题
I am aware of this question, but I believe my concerns are very different.
I recently created an SDL application, using threading and OpenGL. I have one thread running in a loop, which continually updates the state of the objects I draw to the screen. The states are very simple, it is just a boolean array (when the array value is true, I draw it, when it is false, I don't).
Currently, I have no mutex lock on any of my variables and everything is working just fine. Even if only half of the state array was updated between a draw, the framerate is much higher (or at least equal to) the update rate, so it would be acceptable to have a half-updated state.
Now, I initially started working on a similar idea to this on an embedded system using interrupts. Every once in a while, an interrupt would trigger, update the state array, and the execution would continue. Now that I'm on a multi-core desktop, and updating the array simultaneously, I'm wondering why nothing bad is happening, since I am technically reading and writing to the same memory location at the same time.
- Is it just by chance, or is there a reason there's no memory access violations happening?
- If it is acceptable for the state of the variable to change just before, during, or just after the value is used, should I bother using a mutex lock?
Thank you for your help.
Edit: Additional information - the array is created dynamically, but when it is created/deleted, I do use a mutex (I figured accessing deleted memory wouldn't be looked kindly upon :P).
回答1:
In theory, it's completely invalid (undefined behavior) to access memory like this without some synchronization.
In practice, it's moderately safe as long as:
- Only one thread is writing and the others are all reading.
- You don't care if the readers don't see some of the changes made until sometime later (possibly much later than the actual time they're written.
- You don't care if the readers see out-of-order changes, i.e. they see some changes that were made later without seeing other changes that were made earlier.
Issues 2 and 3 are a non-issue on x86, but can occur on nearly every other real-world multi-core/SMP machine. You could mitigate them with some machine-specific asm (or compiler intrinsics) to insert memory barriers at appropriate points.
回答2:
The boolean array elements are can be set/read with an atomic operation, there is not need for a mutex. You need a mutex to protect a structure to make sure that it stays consistent. Since your booleans are independent there is no problem.
来源:https://stackoverflow.com/questions/6935208/should-i-lock-a-variable-in-one-thread-if-i-only-need-its-value-in-other-thread