Locking for each property
I am looking at some code that I do not understand.
private object myProperty_lock = new Object();
private SomeType myProperty_backing;
public SomeType MyProperty
{
get { lock(myProperty_lock) { return myProperty_backing; } }
set { lock(myProperty_lock) { myProperty_backing = value; } }
}
- This pattern is used many times in the same class.
- Each time this pattern is used, a new lock object appears. (This is not a shared lock object for all properties.)
- The types used are reference types and primitives. (No primitive structures.)
Does this code help? References and primitives are assigned atomically, so we don't need to protect against a thread switch in the middle of a job. The lock object is not used anywhere, so there is no protection there.
Maybe there is something with memory barriers? I assumed that blocking within a method does not affect things outside of that method.
source to share
The fact that the code inside the method does not imply a memory barrier. This way, you might be on the right track, suspecting that the locks are for this fresh read memory.
Of course, it could also have been added due to the fact that the person added that it was a cargo cult programmer and did not understand why to do this and did it only because he saw an example of code that does it.
source to share
The problem I see here is that when used, the lock
developer points out a thread safety issue. They thought that parallel threads could access this property.
My first question will be, is this really the case - is there concurrent access to this property?
There might be a valid scenario, but is there a reason any number of threads can install this link? What logic happens if one thread sets a property, seemingly for some good reason, only to be immediately overwritten by another thread? How does an application do something predictable? Was the link given by the previous caller just unimportant? Then why did he set the property?
What about an object - SomeType
- returned from a property? Now, any number of streams can reference the same instance. Can it SomeType
be modified, and if so, is it thread safe?
I'm usually not surprised, but when I see something weird with multithreading, I like to dig a little deeper. They may have it all patched up and it works, but sometimes they don't.
source to share