问题
I would like to know if there are any guidelineswhich a developer should follow as to when (and where) to place locks.
For instance: I understand that code such as this should be locked, to avoid the possibility of another thread changing the value of SomeHeapValue unexpectedly.
class Foo
{
public SomeHeapObject myObject;
public void DoSummat(object inputValue_)
{
myObject.SomeHeapValue = inputValue_;
}
}
My question is, however, how deep does one go with the locking? For instance, if we have this code:
class Foo
{
public SomeHeapObject myObject;
public void DoSummat(object inputValue_)
{
myObject.SomeHeapValue = GetSomeHeapValue();
}
}
Should we lock in the DoSummat(...) method, or should we lock in the GetSomeHeapValue() method?
Are there any guidelines that you all keep in mind when strcturing multi-threaded code?
回答1:
The best guide for locking and threading I found, is this page (this is the text I consult when working with locking and threading):
http://www.albahari.com/threading/
Yo want the paragraph "Locking and Thread Safety", but read the rest also, it is very well written.
回答2:
Lock as little as possible, but as much as needed.
Avoid locks when possible - in .NET 4.0 there are alternatives that are not causing a context switch.
Try not to lock multiple times. Structure your API accordingly. For example a queue. DeQueue - make an alternative DeQueue(int amount) that can dequeue many items with one lock.
来源:https://stackoverflow.com/questions/2779703/guidelines-of-when-to-use-locking