In my multi-threading paranoia I came to the following pattern:
if (c > iCycle)
{
lock (loadStatusLock)
{
if (c > iCycle)
{
c = 0;
p = i.GetRatio(l);
output.AppendLine("Done: " + p.ToString("P2"));
}
}
}
The reasoning behind: The outer if is there so I don't lose performance with lock when the criterion is not met anyway. The inner if is there to prevent other threads that might be waiting there, inside the outer if while the first thread done the inner code.
My question is: does this makes any sense?
Is the reasoning right or I got the mechanics of this wrong. The code above is just example, I started to use this pattern for many situations (I mean: don't look at the particular code, but rather pattern of the nested if/lock/ifs).
Usually I would use lock/if approach as the safest - but then I read so many performance warnings about excessive locking - and, not this code example but other procedure, I have to run about 9 million times so the performance issue comes forward. Later I used if/lock pattern but it is messy because I was getting (or at least I tripped that) threads inside the if scope, waiting for lock and then things gone wild.
What do you guys say on this?
Thanks.
Aucun commentaire:
Enregistrer un commentaire