Note that there are some explanatory texts on larger screens.

plurals
  1. POAvoid blocking with state variable copies?
    primarykey
    data
    text
    <p>I'd like some wisdom regarding a recent multithreading idea of mine. Here goes:</p> <p>Suppose I have the following (pseudo) class whose <code>run()</code> method is chugging away forever on some thread. Other threads will at random times change the state of the <code>Foo</code> instance using <code>setState()</code>. The work that <code>run()</code> is doing only involves reading the state variables, no writing, and the state must not change during one execution of the while statement (example: drawing on a bitmap).</p> <p>In this case, having 2 copies of the state variables seems to prevent a lot of potential blocking (since if I only had one copy of shared state variables, I would have to synchronize everything in the while loop (using <code>stateLock</code>) and outside threads may not get the chance to change the state). Questions after the code break.</p> <pre><code>class Foo { Object stateLock = new Object(); private float my1, my2, my3; private float sh1, sh2, sh3; // sh stands for shared public void setState(...) { synchronized (stateLock) { // modify sh1, sh2, or sh3 here } } private void updateState() { synchronized (stateLock) { // set my1=sh1, my2=sh2, my3=sh3 } } public void run() { while(true) { updateState(); // then do tons of stuff that uses my1,my2,my3 over and over... ... } } } </code></pre> <p>Any holes in this logic? Is there a "standardized" or smarter way of doing this? What if there are tons of state variables? Worse, what if state variables are custom objects that don't copy easily (e.g. in java where variables of custom objects are references)?</p> <p>By the way, this comes from my current work with a SurfaceView in Android.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload