Avoid the use of
: hidden dangers in multi -threaded programming lock(this)
Microsoft documents are clearly recommended to avoid the use of
lock(this)
The problem of uncontrolled locking
The core of the problem is that it is impossible to control which other threads may lock the same object. This can easily lead to dead locks. Multiple threads wait for each other to release the lock, which eventually causes the system to freeze.
Assume that an object is exposed publicly, anyone can get its reference. If any of these references is used to lock the object, the creator of the object may know nothing about it, which will complicate parallel execution and may cause accident errors.Destroy the encapsulation and reduce the clarity
Using the illegal packaging principle, the locking mechanism is exposed to public access. This makes it difficult to understand the expected use and behavior of the object. On the contrary, locking with private fields can provide clearer separation of attention points and ensure that locking internally without exposure to unnecessary implementation details. Danger of misunderstandings and string
lock(this)
Some misunderstandings have inadvertently contributed to the use of
statement is only to identify the key to identify the lock object. Another trap is to try to use a string as a key in the
statement. Because the string is unchanged and shared between applications, this approach may lead to unexpected lock conflicts. Instead, it is best to use private objects as keys to better control the lock mechanism.
lock(this)
Case Study: The thread security in parallel treatment lock
In order to explain the potential problem, please consider the following C#code: lock
In the main method, create multiple threads, and each thread tries to perform operations on the object. Method to try to use the lock of the object of
obtaining the object. However, the and methods also try to lock the object directly or indirectly, and use theas the key. This will lead to unexpected lock conflicts and dead locks, because the code tries to perform operations on it when locking the object of another thread. (It is assumed that the Timewarp and NameChaange methods also use LOCK and use this or Person.name as the lock object. The original text did not provide a complete code)
<code class="language-csharp">public class Person { public int Age { get; set; } public string Name { get; set; } public void LockThis() { lock (this) { System.Threading.Thread.Sleep(10000); } } }</code>
to destroy thread security and create potential deadlocks. Using private field packaging locking mechanisms, and using private objects as keys in the Person
statement, it can provide a more robust and reliable thread synchronization method. LockThis
The above is the detailed content of Why is `lock(this)` Dangerous in Multithreaded Programming?. For more information, please follow other related articles on the PHP Chinese website!