I furrowed my brow at that, too, but then I realized what I think he meant. If you use multiple threads that touch the same data in memory, that will yield better locality than if you had to marshall data across the process boundary.
This doesn't use threading, just a thread-local variable (i.e. a variable that points to different memory locations for each thread) to make the whole thing threadsafe.
I had originally written about threading and locality but it made the post too long and complicated, so I cut it out for the final draft. You can see remnants of it if you check the HTML comments in the post :D
That imposes an uncalled for runtime overhead. A better way would be to implement it using code-patching, by overwriting the instructions at specific pre-determined locations which will then cause the thread to halt when executed.
Not tearing, but it could reorder the assignment so that it happens someplace else than you think it will. For this kind of thread synchronization memory barriers should be used at least.
The physics thread (with interleaved joystick read code on PC) did have to yield back to the main/graphics thread. That was no issue in our case; I've not thought deeply about it, but it seems like the method is likely extensible to do context switches among multiple [unaware/non-cooperating] threads.
> In theory you could take thread priority into account by observing and resetting the dirty/accessed bits every context switch, but this would be unlikely to be worth it.
That would be most likely terrible (as you suggest). You might have better luck giving each thread a copy of the process page table, and keeping that in sync somehow (which also sounds terrible, but might be more workable)
You can get that effect by pinning processors to threads and you can do the sync yourself with a barrier (like Java CyclicBarrier, not a memory barrier.)
The threads could take a pointer/reference to the "stop variable" and use the reference instead of accessing the global variable directly. That allows you to mitigate many problems of global variables. Sorry, if you already do this.
The threads example in another comment is way better
reply