5
\$\begingroup\$

I have both the regular for each loop and its equivalent paralleled version. The loop simply iterates through a collection, looking for the rate key in a local db instance and then updating the topic code.

using (var db = new SomeEntities())
{
    foreach (var measure in measures)
    {
        var keytofind= measure.RateKey.ToString(CultureInfo.InvariantCulture);
        var firstOrDefault = db.RatesMappings.FirstOrDefault(r => r.RateKey == keytofind);
        if (firstOrDefault != null)
            measure.TopicCode = firstOrDefault.TopicCode;
    }

    Parallel.ForEach(measures, measure=>
    {
        var keytofind= rawDataMeasure.RateKey.ToString(CultureInfo.InvariantCulture);

        lock(measure)
        {
            var firstOrDefault = db.RatesMappings.FirstOrDefault(r => r.RateKey == keytofind);
            if (firstOrDefault != null)
                measure.TopicCode = firstOrDefault.TopicCode;
        }
    });
}

Is the paralleled code correct and has the lock been placed correctly?

\$\endgroup\$
10
\$\begingroup\$

No, when you use the lock like that, it's completely useless. Each lock would get its own identifier, so none of he locks would keep any other thread out. To make the lock work at all, you need to use the same identifier for all locks. Demonstration:

object sync = new Object();
var keytofind = rawDataMeasure.RateKey.ToString(CultureInfo.InvariantCulture);
Parallel.ForEach(measures, measure => {
  lock(sync) {
    var firstOrDefault = db.RatesMappings.FirstOrDefault(r => r.RateKey == keytofind);
    if (firstOrDefault != null) {
      measure.TopicCode = firstOrDefault.TopicCode;
    }
  }
});

However, if you need a lock around the code in a parallel loop, then the parallel loop is pointless. The reason that you use the parallel loop is that several threads can run at once, and the lock would prevent that.

\$\endgroup\$
  • \$\begingroup\$ so, do I need the lock to begin with, or should I just put the lock around the measure.TopicCode = firstOrDefault.TopicCode? \$\endgroup\$ – user38158 May 25 '14 at 9:26
  • \$\begingroup\$ I researched the following article link, and it seems each thread should get its own copy of measure so a lock is not required to begin with \$\endgroup\$ – user38158 May 25 '14 at 9:49
  • 2
    \$\begingroup\$ If you only need the lock to protect each measure item to be used from more than one thread, then you don't need the lock at all. Each thread will have its own item. Unless of course you have multiple references to the same object in measures. \$\endgroup\$ – Guffa May 25 '14 at 9:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.