Confusion about the lock statement in C#

后端 未结 6 1274
孤独总比滥情好
孤独总比滥情好 2020-12-05 18:27

This is from MSDN: The lock keyword ensures that one thread does not enter a critical section of code while another thread is in the critical sectio

6条回答
  •  不知归路
    2020-12-05 19:27

    It is one and the same critical section.

    lock (synclock)
    {
      // the critical section protected by the lock statement
      // Only one thread can access this at any one time
    }
    

    See lock Statement on MSDN:

    The lock keyword marks a statement block as a critical section by obtaining the mutual-exclusion lock for a given object, executing a statement, and then releasing the lock.


    Or does it mean: The lock keyword ensures that one thread does not enter any critical section of code while another thread is in any critical section. ?

    No. It does not mean that. It means the critical section protected by that lock and that lock alone.


    Update, following code example:

    If you use a single object to lock on, it will lock all critical sections, causing other threads to block until released. In your code example, once the lock in MethodA has been entered, all other threads reaching that lock and the lock on MethodB will block until the lock is released (this is happening because you are locking on the same object in both methods).

提交回复
热议问题