Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>If you use <code>lock (model)</code>, it doesn't mean that other threads won't be able to access <code>model</code>. What it means is that two threads won't be able to execute a section protected by <code>lock (model)</code> at the same time. Because of this, you could use something like <code>lock (model)</code> to protect access to <code>score</code> too.</p> <p><strong>But</strong> that wouldn't work in this case. <code>lock</code> doesn't lock on a variable, it locks on an object and you modify which object <code>model</code> refers to in the loop. Because of that, I thin the best option here is to create another object and lock on that:</p> <pre><code>object model; int score; object modelLock = new object(); Parallel.For(…, (…) =&gt; { int tempScore=0; Object tempModel=getModel(); //some interesting stuff modifying value of tempScore lock (modelLock) { if(tempScore &gt; score) { score=tempScore; model=tempModel; } } }); </code></pre> <p>If you find out that this is too slow for your needs (because using <code>lock</code> does have some overhead, which might be significant for you), you should consider using something like <a href="http://msdn.microsoft.com/en-us/library/system.threading.thread.volatileread" rel="nofollow"><code>Thread.VolatileRead()</code></a> or <a href="http://msdn.microsoft.com/en-us/library/system.threading.interlocked.compareexchange" rel="nofollow"><code>Interlocked.CompareExchange()</code></a>. But be very careful with them, because it's very easy to make your code subtly wrong.</p>
    singulars
    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. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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