Lock, interlocked

Source: Internet
Author: User
Keywords:
Lock: software lock to prevent multiple threads from accessing the same segment Code .
Interlocked: Provides atomic operations for variables shared by multiple threads.

When multiple threads are required to execute the same piece of code, access may occur simultaneously, and a conflict may occur.
To avoid conflicts, vs. net uses the software lock ).
The software lock allows only one thread to access the code at the same time.
If other threads access this code at this time, the system will change to sleep.
The second access thread will be awakened only after the first access thread ends its access to this code.
And so on.

Usage
Public static int s_callcount = 0;
Public void setcallcount ()
{
Lock (this) // here is the meaning of locking the entire object
{
S_callcount ++;
}
}

Private arraylist m_pages = new arraylist ();
Public void setcallcount (datatable ppage)
{
Lock (this. m_pages) // here is the meaning of locking the array list object
{
This. m_pages.add (ppage );
}
}

Lock (object)
The objects here can be referenced objects such as arraylist and class.

If it is a numeric object, it is best to append the modifier (Private Static) for setting.

For multi-threaded shared values, you can use the interlocked class to read the values or automatically add one or lower the values.

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.