C# multi-threading: Acquire read lock necessary?

C#Multithreading

C# Problem Overview


Is it necessary to acquire a lock on a variable before reading it from multiple threads?

C# Solutions


Solution 1 - C#

The short answer is: it depends.

The long answer is:

  • If it is not a shared value, i.e, only one thread can see it (or use it), you don't need any synchronization.

  • If it is an immutable value, i.e., you set it only once and then only ever read, it is safe to do so without synchronization (as long as you don't start reading before the first write completes).

  • If it is a "primitive" type of at most 32-bits (e.g. byte, short, int) you can get stale (old) data when reading. If that doesn't bother you, you're set. If stale data is undesirable, making the variable volatile can fix this problem without additional synchronization for reads. But if you have racing writers, you will need to follow the same advice as for longs below.

  • If it is a "primitive" type longer than 32-bits (e.g. long, decimal, double) you need synchronization, otherwise you could read "half" of one value, "half" of another, and get crazy results. For this the recommended approach is to use the methods in the Interlocked class, for both reads and writes..

  • If it is a reference type, you will need synchronization to avoid seeing an invalid state (Jeff Lamb's picture example is a good one). The lock statement might be enough for that. Again, you need to lock for both reads and writes.

There are some other points to consider (how long to lock, for example), but I think these are enough to answer your question.

Solution 2 - C#

It depends on the type of variable and your platform. For example, reading Int64s is not guaranteed to be atomic on 32 bit machines. Hence, Interlocked.Read.

Solution 3 - C#

If the loading of the value is done in 1 assembly instruction, it's not necessary to get a lock. You don't care if the value changed 10 minutes ago or 1 microsecond ago. You just want the value now.

However, if you're loading a HUGE array or picture or something, it'd probably be a good idea to lock it out. In theory, you can get preempted while loading the data and have half of the first item and half of the second item.

If it's a simple variable, though, like a bool or int, it's not necessary.

Solution 4 - C#

In adition to the answers below you can also do a read lock using the ReadWriterLockSlim.

That would allow you to do only a read lock when reading and a write lock when modifying your variable. Multiple threads can have a read lock at the same time but as soon as a thread requests a write lock all new request are blocked until it is complete.

This sort of locking would be usefull if you are doing alot of reads and not many writes.

As with most multithreading issues, research it enough to understand if it really fits your problem the ReadWriterLock would not be suitable for every locking situation.

Solution 5 - C#

Reading does not require a lock; as long as you don't care about the 'correctness' of the read. It is only dangerous if you attempt to write without a lock.

Solution 6 - C#

It depends on whether or not is it a local or shared variable, and whether something else may write to it in the meantime, and what you're going to do after reading it.

If you make a decision based on the variable, consider that the next line of code may then be based on data which is now stale.

Solution 7 - C#

Answer is it depends. If the value of the variable does not change when the threads are accessing the variable. otherwise, its needed.

Also, You can use Interlocked.XXX series for maintaining atomicity in reading\writing the variable .

Solution 8 - C#

If it is a constant, no.

If it is an updatable value, yes, if you need consistency.

For updatable values where the exact value must be managed, then yes, you should use a lock or other synchronization method for reads and writes; and perhaps block during the entire scope where the value is used.

Solution 9 - C#

It is 100% necessary unless you are 100% sure that the variable's value won't change while the reader threads are running.

Solution 10 - C#

Necessary? No.

...but if it's possible that another thread could try to write to it during the read (like a collection, etc.) then it might be a good idea.

Solution 11 - C#

As long as it doesn't change during others threads execution you don't need to lock it. If change, you should use it.

Solution 12 - C#

If the variable is never written to by someone (at least at the time it is accessible), you don't need to lock it, because there are no possibilities for missed updates. The same goes if you don't care about missed updates (meaning it is not a problem if you get an older value). Otherwise you should use some sort of synchronization

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAndré HauptView Question on Stackoverflow
Solution 1 - C#R. Martinho FernandesView Answer on Stackoverflow
Solution 2 - C#Kent BoogaartView Answer on Stackoverflow
Solution 3 - C#Jeff LambView Answer on Stackoverflow
Solution 4 - C#GlennView Answer on Stackoverflow
Solution 5 - C#John KraftView Answer on Stackoverflow
Solution 6 - C#Winston SmithView Answer on Stackoverflow
Solution 7 - C#aJ.View Answer on Stackoverflow
Solution 8 - C#meklarianView Answer on Stackoverflow
Solution 9 - C#Ed PowerView Answer on Stackoverflow
Solution 10 - C#Justin NiessnerView Answer on Stackoverflow
Solution 11 - C#MaLKaV_eSView Answer on Stackoverflow
Solution 12 - C#GrizzlyView Answer on Stackoverflow