Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Guidelines of when to use locking

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?

like image 397
miguel Avatar asked May 06 '10 08:05

miguel


People also ask

When would you use the lock keyword?

The lock keyword is used to get a lock for a single thread. A lock prevents several threads from accessing a resource simultaneously. Typically, you want threads to run concurrently. Using the lock in C#, we can prevent one thread from changing our code while another does so.

Why lock is used in threading?

A lock allows you to force multiple threads to access a resource one at a time, rather than all of them trying to access the resource simultaneously.

Why do we use lock statement in C?

The lock statement acquires the mutual-exclusion lock for a given object, executes a statement block, and then releases the lock. While a lock is held, the thread that holds the lock can again acquire and release the lock. Any other thread is blocked from acquiring the lock and waits until the lock is released.

Why should you avoid the lock keyword?

Avoid using 'lock keyword' on string object String object: Avoid using lock statements on string objects, because the interned strings are essentially global in nature and may be blocked by other threads without your knowledge, which can cause a deadlock.


2 Answers

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/

You want the paragraph "Locking and Thread Safety", but read the rest as well, it is very well written.

like image 191
user218447 Avatar answered Oct 13 '22 01:10

user218447


  • 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.

like image 22
TomTom Avatar answered Oct 13 '22 00:10

TomTom