Art of multi-processor programming Reading Notes (2)-mutex

Source: Internet
Author: User
Mutex is a multi-processor. Program The most common collaboration method in design. We put a resource into the critical section: A single point of time can only be executed by one thread. This feature is called mutex. The standard method for implementing mutex is to use an ilock object with the following interfaces. Public   Interface Ilock
{
Void Setlock ();
Void Unlock ();
}

Public class counter
{
Private int _ value;
Private ilock _ lock;

Public int getandincrement ()
{
_ Lock. setlock ();
Try
{
Int temp = _ value;
_ Value = temp + 1;
Return _ value;
}
Finally
{
_ Lock. Unlock ();
}
}
}

If a thread executes the setlock () method call, the thread obtains a lock (or lock). If the unlock () method call is executed, the thread is called releasing the lock (or unlocking ). In the implementation of the shared counter above, the ilock domain is used to ensure the mutex feature of the object. The thread must call setlock () and unlock () in the specified way (). If a thread meets the following conditions, it is well-structured:
1. A critical section is associated only with a unique ilock object.
2. The setlock () method of the object is called when the thread is about to enter the critical section.
3. Call the unlock () method when the thread leaves the critical section.

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.