BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

Parallel and Asynchronous
.NET 1.1+

Thread-Safety with the Interlocked Class

When developing multi-threaded software or using parallel programming techniques, it is essential that classes remain thread-safe. The Interlocked class provides methods that assist with thread safety by performing atomic operations.

Read

Surprisingly, reading the value of a 64-bit integer is not an atomic operation and, therefore, is not thread-safe. When executing code on a 64-bit processor such reads are atomic and thread-safe. However, when the computer has a 32-bit processor such a read requires separate 32-bit reads from two locations. This means that it is possible, if one thread changes the 64-bit value whilst another is reading it, that simply reading a 64-bit value will yield an incorrect result.

The Read method is available in the .NET framework version 2.0 and later. It ensures that when you read a 64-bit value that you do so in a thread-safe manner. The syntax of the method is as follows:

long value = Interlocked.Read(ref valueToRead);

Interlocked Considerations

All of the Interlocked methods are thread-safe with respect to each other. However, they do not guarantee thread safety when used with other operations. For example, if one thread uses the Increment method whilst another uses the increment operator, it is still possible to get incorrect results. Therefore, when you are using Interlocked methods against shared data you should ensure that all access to that data uses Interlocked methods. If this is not viable, you should use means to synchronise your threads, such as locking critical sections with the lock statement.

29 February 2012