Does lock(){} lock a resource, or does it lock a p

2020-06-08 07:59发布

I'm still confused... When we write some thing like this:

Object o = new Object();
var resource = new Dictionary<int , SomeclassReference>();

...and have two blocks of code that lock o while accessing resource...

//Code one
lock(o)
{
  // read from resource    
}

//Code two
lock(o)
{
  // write to resource
}

Now, if i have two threads, with one thread executing code which reads from resource and another writing to it, i would want to lock resource such that when it is being read, the writer would have to wait (and vice versa - if it is being written to, readers would have to wait). Will the lock construct help me? ...or should i use something else?

(I'm using Dictionary for the purposes of this example, but could be anything)

There are two cases I'm specifically concerned about:

  1. two threads trying to execute same line of code
  2. two threads trying to work on the same resource

Will lock help in both conditions?

7条回答
啃猪蹄的小仙女
2楼-- · 2020-06-08 08:34

Will lock help in both conditions? Yes.

Does lock(){} lock a resource, or does it lock a piece of code?

lock(o)
{
  // read from resource    
}

is syntactic sugar for

Monitor.Enter(o);
try
{
  // read from resource 
}
finally
{
  Monitor.Exit(o);
}

The Monitor class holds the collection of objects that you are using to synchronize access to blocks of code. For each synchronizing object, Monitor keeps:

  1. A reference to the thread that currently holds the lock on the synchronizing object; i.e. it is this thread's turn to execute.
  2. A "ready" queue - the list of threads that are blocking until they are given the lock for this synchronizing object.
  3. A "wait" queue - the list of threads that block until they are moved to the "ready" queue by Monitor.Pulse() or Monitor.PulseAll().

So, when a thread calls lock(o), it is placed in o's ready queue, until it is given the lock on o, at which time it continues executing its code.

查看更多
登录 后发表回答