1. Why lock and what is locked?
When we use threads, the most efficient way is of course asynchronous, that is, each thread runs at the same time, without relying on each other and waiting. However, when different threads need to access a certain resource, a synchronization mechanism is required, that is, when reading and writing the same resource, we need to make the resource only operated by one thread at the same time to ensure that each operation is effective and immediate, that is, to ensure the atomicity of its operation. lock is the most commonly used synchronization method in C#, in the format lock(objectA){codeB}.
lock(objectA){codeB} seems simple, but it actually has three meanings, which is essential for using it appropriately: 1. Is objectA locked? If not, I'll lock it, otherwise wait until objectA is released. 2. After locking, other threads cannot call codeB or use objectA during the execution of codeB. 3. After executing codeB, release objectA, and codeB can be accessed by other threads.
2. What happened to lock(this)?
Let's look at an example:
In the t1 thread, LockMe calls lock(this), that is, c1 in the main function, and when calling lock(c1) in the main thread, it must wait for the lock block in t1 to be executed before accessing c1, that is, all c1-related operations cannot be completed, so we see that even c1. DoNotLockMe() is not executed.
|