简体   繁体   中英

Should I lock a variable in one thread if I only need it's value in other threads, and why does it work if I don't?

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).

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:

  1. Only one thread is writing and the others are all reading.
  2. 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.
  3. You don't care if the readers see out-of-order changes, ie 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM