DientesDeCheto
DientesDeCheto

Reputation: 31

Threads reading and writing same variable

I would like to know if I need a lock for a situation of 2 threads, one reading and the other one writing to same Variable both.
For example: We have 2 Threads: A & B, Thread A reads variable x at time T and Thread B writes variable T at time T. Should I may consider here some type of lock?

In my case I have the Main Thread an many other SubThreads. The Main Thread holds a List<myObj> and before starting any SubThread I create instances of myObj assigning it to the List<myObj> and passing myObj to the SubThread.
At determined moment the List has to be sorted depending on a value contained in myObj, and it can perfectly happen that the List element which is read by the Main Thread, simultaneously is written by a SubThread.

Please some suggestions.

Upvotes: 0

Views: 2975

Answers (1)

Luaan
Luaan

Reputation: 63722

YES

Don't even consider any alternative until you have a deep and thorough understanding of how multi-threading works. Obligatory link: http://www.albahari.com/threading/, at the very least. And unless you have very good reasons, not even then - especially with something as complex as a List.

Any time you're accessing any shared state, make sure that all the ways to share the state are synchronized.

It's possible to use lock-less synchronization, but that's a rather advanced subject, and prone to errors. If you're only updating a primitive value, Interlocked might be good enough.

However, don't forget the contracts of the objects you're working with - List's sort is only safe if the items don't change during the sorting. So before starting the sort, you need to ensure noöne is modifying anything that could change the ordering while the sort is underway.

Do you really need those sub-threads? Do they really need to update the list (/items) from a separate thread? Perhaps posting the change to the UI thread would work well enough, while avoiding those multi-threading issues?

Upvotes: 3

Related Questions