ASP. NET multi-thread programming-multi-thread programming critical section under. NET (8)

Source: Internet
Author: User

Reading directory
I. Critical Section Overview
Ii. critical section operations
Iii. Instances
4. Use the Interlocked class to set the critical section
V. Use the Monitor class to set the critical section
I. Critical Section Overview
In a certain period of time, two threads can be executed at the same time. If both threads access the same data, there may be unnecessary things in this case, for example: my bank account has a total amount of 5000 RMB. One day I took my passbook to the counter to get 4000 RMB for the deposit, and my daughter-in-law took a bank card to get 2000 RMB for the children to pay the tuition fee. At a certain point in time, we both took the money, first, the Bank operates like this. First, it judges that the account balance is greater than 4000 of the amount I want to fetch. Then, we can spit out 4000 oceans for me because it is done at the same time, the daughter-in-law first judges that the account balance is greater than 2000 of the amount she wants to fetch, so she can spit out 2000 oceans for her. In this case, our total account amount is only 5000 yuan, my wife and I took out a total of 6000 yuan, so the 1000 banks who spoke out a lot can only recognize it. The bank's account balance is-1000. We don't want this to happen, so what should we do? This should be the case. First of all, when I get 4000, it is locked, that is, the lock we often say. When the daughter-in-law gets 2000 at the same time point, it cannot be obtained, after I get the lock, the lock is released, and the daughter-in-law can take it. When the daughter-in-law gets 2000, the system will prompt that the remaining balance is 1000, and 2000 cannot be extracted, here, the critical section refers to the region where the data is operated.
Ii. critical section operations
The. Lock keyword marks a statement block as a critical section, and another thread cannot enter the critical section.
The. Interlocked class provides atomic operations for variables shared by multiple threads.
The. Monitor class provides synchronous access to objects. The Monitor class controls access to objects by setting an object lock to a single object, and uses Enter and Exit to mark the beginning and end of a critical section.
Iii. Instances
When we cancel the Lock keyword, an exception is reported because _ money is a negative number, that is, the existing account amount is a negative number, and the bank money is a negative number, we don't cancel Lock. keyword 2 is running normally. Why? The red code and the yellow code are atomic operations. When a thread accesses the red code, because it is executed in parallel, other threads also come in to reduce the money, if no lock keyword exists, both threads can execute the yellow code section, such as this. when _ money is reduced to 500, because intAmount is always 500, if (this. _ money> = intAmount) is true, so both threads can enter the if statement block to do the yellow part of the code, that is, this. _ money = this. _ money-intAmount, the first Thread 0 = 500-500, the second thread-500 = 0-500, and the connection is reduced twice, so the last this. _ money is negative, so we need to add the lock keyword to allow only one thread to come in at a time point.
Using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. Text;
Using System. Threading;
Namespace CriticalZone
{
Public class Money
{
Public int _ money; // The current account amount.

/// <Summary>
/// Initialize the total account www.2cto.com
/// </Summary>
/// <Param name = "intTotalMoney"> total account amount </param>
Public Money (int intTotalMoney)
{
This. _ money = intTotalMoney;
}
/// <Summary>
/// Determine whether the remaining money of the bank is negative. If it is negative, an exception is thrown. If it is not negative, the Bank continues to withdraw the money.
/// </Summary>
/// <Param name = "intAmount"> amount to be taken away </param>
/// <Returns> </returns>
Public int Withdraw (int intAmount)
{
If (this. _ money <0)
{
Throw new Exception ("the bank's money is negative ");
}
Return UseLock (intAmount );
}
Public int UseLock (int intAmount)
{
// You can comment out the lock to see the effect.
Lock (this)
{
// If the bank's money is greater than or equal to the amount to be taken away, the money will be reduced
If (this. _ money> = intAmount)
{
Thread. Sleep (5 );
This. _ money = this. _ money-intAmount;
Return intAmount;
}
Else
{
Return 0;
}
}
}
/// <Summary>
/// Money collection
/// </Summary>
Public void GetMoney ()
{
// 100 RMB in cash for 500 consecutive times, so for the moment, the total account amount is 5000 RMB, and it can only be obtained ten times, and the account is 0, the amount should not be reduced.
For (int I = 0; I <100; I ++)
{
Withdraw (500 );
}
}
}
Class Program
{
// Declare ten threads, which is equivalent to ten people taking money at the same time
Static Thread [] threads = new Thread [10];
Static void Main (string [] args)
{
Money money = new Money (5000 );
// Create ten threads. These ten threads do the same thing. GetMoney takes money.
For (int I = 0; I <10; I ++)
{
Thread thread = new Thread (new ThreadStart (money. GetMoney ));
Threads [I] = thread;
}
// Run ten threads at the same time
For (int I = 0; I <10; I ++)
{
// Start to execute GetMoney ()
Threads [I]. Start ();
}
Console. WriteLine ("thread started ");
Console. ReadLine ();
}
}
}

}
  
                      Figure 1
  

Figure 2


 

4. Use the Interlocked class to set the critical section

V. Use the Monitor class to set the critical section

Learn a little bit every day, make a little progress every day, record work with words, and record life with words
 

From childhood sleepy

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.