0

Original code:

var can = rateLock.WaitAsync();
if (can.IsCompletedSuccessfully) // for safety but do I need it?
{
    if (!increase)
    {
        errorRate = (byte)(errorRate - Convert.ToByte(errorRate > 0));
    }
    else
    {
        errorRate++;
    }
    if (errorRate > 50)
    {
        TimerStop(true);
    }
    rateLock.Release();

}

Modified to:

if (increase)
{
    if (Interlocked.Increment(ref errorRate) > 50)
    {
        TimerStop(true);
    }
}
else
{
    Interlocked.Exchange(ref errorRate, (errorRate - Convert.ToInt32(errorRate > 0)));
}

The problem: As you can see, the "decrementing" part relies on the same variable value that needs to be read twice, then boolean and substraction operations performed and all of this outside of Interlocked context.

I really liked possibility of having no extra SempahoreSlim (async env) - is there any way to make decrementing work with custom condition avoiding tons of IFs (I need to keep errorRate >=0)?

1
  • Well yeah I have an ugly version1 I guess I will stick with. I was hoping this would be viable: hastebin.com/kukohorumi.cs but I think that equality check still can screw me up
    – KreonZZ
    Commented Aug 18, 2018 at 22:02

1 Answer 1

1

You can use the CompareExchange pattern for more complex operations:

int initialErrorRate, int computedErrorRate;
do
{
  initialErrorRate = errorRate;
  if (increase)
  {
    computedErrorRate = initialErrorRate + 1;
  }
  else
  {
    computedErrorRate = initialErrorRate - Convert.ToInt32(initialErrorRate > 0);
  }
}
// set new error rate only when it was not changed inbetween, otherwise try again
while (initialErrorRate != Interlocked.CompareExchange(ref errorRate, computedErrorRate, initialErrorRate);

if (errorRate > 50)
{
  TimerStop(true);
}
2
  • What if errorRate needs to be zeroed after it is over 50? This is what I came up with: ghostbin.com/paste/dkdup
    – KreonZZ
    Commented Aug 19, 2018 at 8:02
  • The value changes itself are thread-safe, but if you call it twice like in your link then errorrate may be incremented or decremented twice. What to do depends if calling TimerStop twice or more is okay or not, if it’s not I doubt it’s possible to do without locks. If it’s okay to call TimerStop multiple times and it’s completing fast, you may move it into the loop.
    – ckuri
    Commented Aug 19, 2018 at 8:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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