Steve Townsend
Steve Townsend

Reputation: 54148

Can Interlocked class safely be mixed with lock()?

Is an atomic read guaranteed when you mix Interlocked operations with lock() (and other higher-level locks)?

I am interested in general behaviour when mixing locking mechanisms like this, and any differences between Int32 and Int64.

private Int64 count;
private object _myLock;

public Int64 Count 
{
  get 
  {
    lock(_myLock)
    {
      return count;
    }
  }
}

public void Increment
{
  Interlocked.Increment(ref count);
}

Upvotes: 8

Views: 1400

Answers (6)

Szynkie
Szynkie

Reputation: 79

You can NOT safely mix lock with Interlock. Example here:

using System;
using System.Threading.Tasks;
using System.Threading;

public class Program
{
    public static void Main()
    {
        object lockObj = new object ();
        var IncrementValue = 0;
        Parallel.For(0, 10000, x =>
        {
            //Incrementing the value
            if (x % 2 == 0)
            {
                lock (lockObj)
                {
                    IncrementValue++;
                }
            }
            else
                Interlocked.Increment(ref IncrementValue);
        });
        Console.WriteLine("Expected Result: 10000");
        Console.WriteLine("Actual Result: " + IncrementValue);
    }
}

Output:

Expected Result: 10000
Actual Result: 9997

If you change both incrementing to lock or both to Interlock it will work fine.

Upvotes: 3

Jon Hanna
Jon Hanna

Reputation: 113242

Note: This answer (including the two edits already) was given before the question was changed to have a long count. For the current question instead of Thread.VolatileRead I would use Interlocked.Read, which also has volatile semantics and would also deal with the 64-bit read issue discussed here and introduced into the question

An atomic read is guaranteed without locking, because reads of properly-aligned values of 32-bit or less, which your count is, are guaranteed to be atomic.

This differs from a 64-bit value where if it started at -1, and was read while another thread was incrementing it, could result in the value read being -1 (happened before increment), 0 (happened after increment) or either of 4294967295 or -4294967296 (32 bits written to 0, other 32bits awaiting write).

The atomic increment of Interlocked.Increment means that the whole increment operation is atomic. Consider that increment is conceptually:

  1. Read the value.
  2. Add one to the value.
  3. Write the value.

Then if x is 54 and one thread tries to increment it while another tries to set it to 67, the two correct possible values are 67 (increment happens first, then is written over) or 68 (assignment happens first, then is incremented) but non-atomic increment can result in 55 (increment reads, assignment of 67 happens, increment writes).

A more common real case is x is 54 and one thread increments and another decrements. Here the only valid result is 54 (one up, then one down, or vice-versa), but if not atomic then possible results are 53, 54 and 55.

If you just want a count that is incremented atomically, the correct code is:

private int count;

public int Count 
{
  get 
  {
    return Thread.VolatileRead(byref count);
  }
}

public void Increment
{
  Interlocked.Increment(count);
}

If however you want to act upon that count, then it will need stronger locking. This is because the thread using the count can become out of date before its operation is finished. In this case you need to lock on everything that cares about the count and everything that changes it. Just how this need be done (and whether its even important to do at all) depends on more matters of your use-case than can be inferred from your question.

Edit: Oh, you may want to lock simply to force a memory barrier. You may also want to change Count's implementation to return Thread.VolatileRead(ref count); to make sure CPU caches are flushed if you are going to remove the lock. It depends on how important cache staleness is in this case. (Another alternative is to make count volatile, as then all reads and writes will be volatile. Note that this isn't needed for the Interlocked operations as they are always volatile.)

Edit 2: Indeed, you're so likely to want this volatile read, that I'm changing the answer above. It is possible you won't care about what it offers, but much less likely.

Upvotes: 11

Eric Lippert
Eric Lippert

Reputation: 660030

Is an atomic read guaranteed when you mix Interlocked operations with lock() (and other higher-level locks)?

An atomic read of int is always guaranteed regardless of locking of any kind. The C# specification states that reads of ints are always atomic.

I think that your actual question is different than the one you asked. Can you clarify the question?

Upvotes: 3

R. Martinho Fernandes
R. Martinho Fernandes

Reputation: 234434

First, you can't lock on value types, like int.

When you lock on a value type, it gets boxed into an object first. The problem is that it will be boxed every time and every time it will be a different "box". You will be locking on a different object every time, rendering the lock block useless.

That problem aside, let's say you you lock on a reference type, and you use the Interlocked class on another thread. There will be no synchronization between the threads. When you want synchronization you must use the same mechanism on both threads.

Upvotes: 2

Bryan
Bryan

Reputation: 2791

The answer to your question is no. The lock and Interlocked don't have anything to do with each other and they do not work together in the manner you are suggesting.

Also, not sure what is going on with your code. It does not compile. You can't lock on a value type. Also, Increment() takes a ref argument.

Upvotes: 2

Alex F
Alex F

Reputation: 43311

The argument provided to the lock keyword must be an object based on a reference type. In your code, this is value type, this possibly means boxing, which makes lock statement useless.

Interlocked operation is atomic relatively to another Interlocked operation running in another thread, and applied to the same variable. There is no thread safety, if one thread uses Interlocked operation, and another changes the same variable by using another synchronization algorithm, or without synchronization.

Upvotes: 3

Related Questions