In my C# program, I have got method code:
Object model;
int score;
for()
{
int tempScore=0;
Object tempModel=getModel();
//some interesting stuff modifying value of tempScore
if(tempScore>score)
{
score=tempScore;
model=tempModel;
}
}
I would like to use Parallel for insted of normal, but I'm afraid that i will encounter some synchronization issues. I know that I can use lock(model), but what can I do about simple type score? model and score are method local variables, therefore they are shared between threads.
If you use
lock (model)
, it doesn't mean that other threads won't be able to accessmodel
. What it means is that two threads won't be able to execute a section protected bylock (model)
at the same time. Because of this, you could use something likelock (model)
to protect access toscore
too.But that wouldn't work in this case.
lock
doesn't lock on a variable, it locks on an object and you modify which objectmodel
refers to in the loop. Because of that, I thin the best option here is to create another object and lock on that:If you find out that this is too slow for your needs (because using
lock
does have some overhead, which might be significant for you), you should consider using something likeThread.VolatileRead()
orInterlocked.CompareExchange()
. But be very careful with them, because it's very easy to make your code subtly wrong.