Use the Lock keyword in C #

Source: Internet
Author: User

Use the Lock keyword in C #
Zookeeper

I. Lock Definition

The lock keyword can be used to ensure that the code block is executed without being interrupted by other threads. It can define a piece of code as a critical section. A mutex section allows only one thread to run at a time, while other threads must wait. This is achieved by obtaining mutex locks for a given object during the code block operation.

In multiple threads, each thread has its own resources, but the code zone is shared, that is, each thread can execute the same function. This may cause several threads to execute a function at the same time, resulting in data confusion and unexpected results. Therefore, we must avoid this situation.

While in. NET, it is best to understand the process, application domain and thread concepts, Because Lock is for the Thread level, and in. is the application domain in NET isolated from Lock? I guess that threads in different application domains cannot be interrupted through Lock; in addition, it is best to understand the concepts of data segments, code segments, stacks, and stacks.

The C # lock keyword is defined as follows:

Lock (expression) statement_block, where expression represents the object you want to trace, usually the object reference.

If you want to protect an instance of a class, generally you can use this; if you want to protect a static variable (such as a mutex code segment inside a static method ), generally, you can use a class name.

The statement_block is the code of the mutex, which can be executed by only one thread at a time.


Ii. Meaning of lock


Lock (objectA) {codeB} seems simple and actually has three meanings, which is important for proper use of it:
1. Is objectA locked? Otherwise, wait until the objectA is released.
2. When codeB is executed after the lock, other threads cannot call codeB or use objectA.
3. After codeB is executed, release objectA and codeB can be accessed by other threads.

Iii. Use of lock

Public class Singleton
{
Private static Singleton _ instance = null;
Private Singleton (){}
Public static Singleton CreateInstance ()
{
If (_ instance = null)

{
_ Instance = new Singleton ();
}
Return _ instance;
}
}

The preceding example defines a singleton example.

However, the preceding example does not consider the issue of concurrent instance acquisition by threads, that is, two threads may obtain instance instances at the same time. If the instance is null, two threads will create instances separately, the Singleton rule is violated. Therefore, you need to modify the above Code.

In this case, you can use LOCK ()

Publicclass Singleton
{
Privatestatic Singleton instance;
Privatestaticobject _ lock = newobject ();

Private Singleton (){}

Publicstatic Singleton GetInstance ()
{

If (instance = null)
{
Lock (_ lock)
{
If (instance = null)
{
Instance = new Singleton ();
}
}
}
Return instance;
}
}

The above Code uses the dual lock method to better solve the implementation of the Singleton mode under multiple threads. First look at the if statement block in the inner layer. When this statement block is used, the lock operation is performed first to ensure that only one thread can access this statement block, and then only one instance is created. Look at the if statement block of the outer layer, so that each thread does not have to lock the instance every time it wants to obtain the instance, because the lock is required only when the instance is empty (that is, an instance needs to be created, if an instance already exists, the instance is directly returned, saving performance overhead.


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.