Multi-threaded programming design mode critical zone Mode

Source: Internet
Author: User

The critical section pattern refers to the mode in which only one thread can be executed in a shared range.
It is the basis of all other multi-threaded design patterns, so I will first introduce it.
Focus on the scope. This mode is called the critical section mode. If you place the eye point on the thread of execution, this mode is called
Single-thread execution mode.

First, let's play a cave drill game. axman, Sager, and pentium4. three of them are at the star anise playground.
In the circular drilling cave (Kao, weight loss training), each person has a sign in his hand. The old man who drilled each hole will put the current order,
The name and number are displayed, and check whether the name and number are consistent.

OK. The participants in this game include geezer, player, US, and Corrie.

Public class geezer {
Public static void main (string [] ARGs ){

System. Out. println ("preparation, start! ");
Corrie c = new Corrie (); // only one cave exists. Therefore, after an instance is saved, it is passed to multiple players.
New player ("axman", "001", c). Start ();
New player ("Sager", "002", c). Start ();
New player ("pentium4", "003", c). Start ();
}
}

This class has nothing to say at the moment. It is a main role.

Public class player extends thread {
Private final string name;
Private final string number;
Private Final Corrie;
Public player (string name, string number, Corrie ){
This. Name = Name;
This. Number = number;
This. Corrie = Corrie;
}

Public void run (){
While (true ){
This. Corrie. Into (this. Name, this. number );
}
}
}
Here, we set all the member fields to final. To demonstrate that once a player is constructed, its name and number cannot be changed.
To put it simply, in the game, I, Sager, and pentium4 won't secretly change their grades or secretly
Drill into another cave. If this game encounters an error, it will not be in our game.

Import java. util .*;
Public class Corrie {
Private int COUNT = 0;
Private string name;
Private string number;
Private hashmap Lib = new hashmap (); // store the name and number

Public Corrie (){

Lib. Put ("axman", "001 ");
Lib. Put ("Sager", "002 ");
Lib. Put ("pentium4", "003 ");
 
}

Public void into (string name, string number ){
This. Count ++;
This. Name = Name;
This. Number = number;
If (this. Lib. Get (name). Equals (number ))
Test ():
}

Public String display (){
Return this. Count + ":" + this. Name + "(" + this. Number + ")";
}

Private void test (){
If (this. Lib. Get (name). Equals (number ))
;
// System. Out. println ("OK:" + display ());
Else
System. Out. println ("Err:" + display ());
}
}

This class adds a hashmap of Lib, which is equivalent to a library with the player name and number. It is known that Corrie only has one instance,
So I used a member object instead of a static instance, just to initialize the content in the library in the constructor method.
This function is implemented in a helper class to encapsulate the data structure. If this Lib is not provided, you need to use it during check.
If (name. equasl ("axman ")){
If (! Number. Equals ("001") // Error
}
Else if .......
For such complex statements, most players may be prone to hand cramps, so using a Lib for chcek is very similar.

It takes some patience to run this program, because it can be correct even if your program is poorly written in many single-threaded testing environments.
In addition, multi-threaded programs behave differently on different machines. It may take a long time to identify the errors in this example. If your
If the machine has multiple CPUs, there will be more opportunities for errors.

The final error occurred in my notebook after 11 minutes. The error occurred for several minutes:
1: Err: axman (003)
2: Err: Sager (002)

The first case is to check the error. My brand number is 001, but 003 is printed. The second case shows no error, but the error is printed.

In fact, according to The multithreading knowledge introduced previously, it is not difficult to understand the error in this example. Because into is NOT thread-safe
After a thread executes this. Name = "axman";, it should have executed this. numner = "001", but is switched to another thread for execution.
This. Number = "003", and then execute an IF (this. Lib. Get (name). Equals (number) in an unpredictable switchover ))
The error 1 is displayed, and the display is not thread-safe when printing this error. to print an incorrect result
This. Name or this. Number. An error occurs when a field is modified to a correct match.

In addition, sequence numbers may be reversed or not matched, but this error cannot be observed intuitively, because you do not know which sequence number "should"
The player to which the serial number is reversed may be covered by the scrolling screen.

[Example of the correct critical section mode]
We know these errors occur because the method of the Corrie class is not thread-safe. You only need to modify the Corrie class to a thread-safe class.
Other classes do not need to be modified. As mentioned above, if an error occurs, it is definitely not for our players:

 

Import java. util .*;
Public class Corrie {
Private int COUNT = 0;
Private string name;
Private string number;
Private hashmap Lib = new hashmap (); // store the name and number

Public Corrie (){

Lib. Put ("axman", "001 ");
Lib. Put ("Sager", "002 ");
Lib. Put ("pentium4", "003 ");
 
}

Public synchronized void into (string name, string number ){
This. Count ++;
This. Name = Name;
This. Number = number;
Test ();
}

Public synchronized string display (){
Return this. Count + ":" + this. Name + "(" + this. Number + ")";
}

Private void test (){
If (this. Lib. Get (name). Equals (number ))
;
// System. Out. println ("OK:" + display ());
Else
System. Out. println ("Err:" + display ());
}
}

Run this example. If you are patient, run your machine for three days. Although the test for 100 days does not indicate that there is no error in 101st days,
At least is more reliable than the original example without synchronized protection!

Here we have an intuitive understanding of the routine of the critical section mode. Before giving a detailed explanation of this mode, please think about it, test
Is the method safe? Why?

 

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.