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.
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).
There is no such thing.
Use the lock keyword to guard code that can be executed simultaneously by more than one thread. public class ClassA { private ClassB b = new ClassB(); public void MethodA() { lock (b) { // Do anything you want with b here. } } public void MethodB() { lock (b) { // Do anything you want with b here. } } }
With locking, deadlock happens when threads acquire multiple locks at the same time, and two threads end up blocked while holding locks that they are each waiting for the other to release.
Locks are a very important feature that make multithreading possible. Locks are a synchronization technique used to limit access to a resource in an environment where there are many threads of execution.
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With