concept lock in category c#

This is an excerpt from Manning's book Code like a Pro in C#.
How to use C# with containerized environments such as Kubernetes and/or Docker. While very practical and used in many enterprise development environments, knowing how to use Kubernetes or Docker does not guarantee you can “code like a pro” in C#. To learn more about these technologies, see Marko Lukša’s Kubernetes in Action. second edition (Manning, 2020), Elton Stoneman’s Learn Docker in a Month of Lunches (Manning, 2020), and Ashley Davis’ Bootstrapping Microservices with Docker, Kubernetes, and Terraform (Manning, 2020).
Locking resources and controlling thread access is the bane of many software engineers’ existence. Code blows up in complexity once you deal with multiple threads because the amount of places errors can crop up increases rapidly. To lessen the burden of developers, C# exposes one statement (
lock) and two primary types of synchronization primitives to save you: mutexes and semaphores.What is their difference and when would you use one over the other? The easiest to use is the standard
lockstatement. To lock a resource using thelockstatement and only allow one thread at a time to operate on it, use thelock([RESOURCE]){…}syntax:decimal netWorth = 1000000; lock(netWorth) { … }The
netWorthvariable is locked for the duration of the lock code block (after the code leaves the code block, the lock is released) and can only be accessed by one thread at a time. It is also worth noting that thelockstatement prohibits two threads to lock the same resource at the same moment. If two threads could instantiate a lock at the same time, a lock would not be able to fulfill its “one thread at a time” promise. This is what we call a deadlock: two threads holding onto the same resource waiting for the other to release that resource. Belaboring the obvious, we try to avoid deadlocks in our code as they are notoriously hard to debug.