Dive into the inner workings of the lock
statement
Developers often use the lock
statement to protect code execution when dealing with non-thread-safe objects. But what exactly happens under the hood when multiple threads interact with this protected code?
Deep Dive: Tracking the Execution of lock
Statements
In C# 3.0, the lock
statement translates to the following code:
<code class="language-C#">var temp = obj; Monitor.Enter(temp); try { // 非线程安全代码 } finally { Monitor.Exit(temp); }</code>
In C# 4.0, this process has been modified and the generated code is as follows:
<code class="language-C#">bool lockWasTaken = false; var temp = obj; try { Monitor.Enter(temp, ref lockWasTaken); // 非线程安全代码 } finally { if (lockWasTaken) { Monitor.Exit(temp); } }</code>
Monitor.Enter
Function
Monitor.Enter
plays a vital role in the functionality of the lock
statement. MSDN describes its operation as follows:
" Use Enter
to get the Monitor
of the object passed as argument. If another thread has already executed a Enter
for the object but has not yet executed the corresponding Exit
, the current thread will block until another The thread releases the object ”
Essentially, Monitor.Enter
guarantees exclusive access to the object. If another thread tries to acquire the same lock, it will be suspended until the lock is released. Multiple calls to Enter
from the same thread will not cause blocking, but require the same number of Exit
calls to unlock the object and allow the waiting thread to resume execution.
Infinite waiting time
It is worth noting that Monitor.Enter
will wait indefinitely for the lock to become available. Unlike some locking mechanisms, it does not enforce a timeout.
The above is the detailed content of How Does the C# `lock` Statement Work Under the Hood?. For more information, please follow other related articles on the PHP Chinese website!