Check the multi-thread synchronization problem of C # from bus congestion

Source: Internet
Author: User

I haven't written a blog for a long time. It may be because my recent work is too depressing! A little decadent... and the company is nearly 40-50 minutes away from its place to take a bus (various reasons, tangle in ing...), get up one and a half hours in advance, can even be late! Because it is a crossroads between the first two stations of the company, where can it be congested for more than 30 minutes every day .... it's coming to the company, and one vehicle is congested .. look at the past 1 minute 1 second .. don't worry about getting cold (late will deduct money !)... The cool pulling reminds me of the synchronous Asynchronization of threads in C. so in this blog post, let's talk about my understanding of Thread Synchronization in C #. If this is not the case, please give me some advice. Thank you first!

What is thread synchronization? When multiple threads run simultaneously, the logic relationship between threads may determine who executes the task first and who executes the task later. This is thread synchronization.

(1) thread priority

When the threads compete for CPU time slice, the CPU serves according to the priority of the thread. Application in C #ProgramThe thread has five different priorities, from high to low: highest, abovenormal, normal, belownormal, and lowest. If the priority is not specified during thread creation, the system defaults to normal.

For example:Thread t = new thread (methodname );

T. Priority = threadpriority. abovenormal;

By setting the thread priority, you can change the thread execution sequence. The set priority only applies to the processes to which these threads belong. (Note: When the priority of a thread is set to htghest, other threads running on the system will be terminated, so be careful when using this priority. Do not use this priority unless the coin needs to be processed immediately ).

(2) thread synchronization

Multi-threaded processing solves the problem of throughput and response speed, but also brings about the problem of resource sharing, such as deadlocks and resource contention. Multithreading is especially suitable for tasks that require different resources (such as file handles and network connections. Allocating multiple threads to a single resource may cause synchronization problems. In this case, the threads may be blocked frequently to wait for other threads, and the original intention of using multiple threads is different.

Synchronization refers to the association between multiple threads in sequence of execution. If a thread can continue to run only after another thread completes a job, you must consider how to keep others synchronized, to ensure that multiple threads run on the system at the same time without deadlock or logical errors.

To solve the synchronization problem, it is generally used to execute time-consuming tasks or time-consuming tasks that do not require a large amount of resources used by other threads. But in fact, some resources in the program must be accessed by multiple threads. To solve these problems, the system. Threading namespace provides multiple classes for Synchronous threads. These classes include mutex, monitor, interlocked, and autoresetevent. But in actual applications, we may not use these classes most, but the lock statement provided by C.

Lock statement

To simplify synchronization in multi-threaded applications, C # provides a lock statement. The lock keyword ensures that when a thread is locatedCodeThe other thread does not enter the critical section. If other threads attempt to enter the locked code segment, it will wait (blocking) until the locked object is released.

PrivateObject OBJ= NewObject ();
.....
Lock (OBJ)
{
//Critical Section
}

For example, we believe that we will better understand that Lu Jia and passers-by B are about to go to the toilet. We just found a public toilet with only one location in the public toilet, passer-by A is a member (with a high priority). First, she slipped in, and then locked the door (LOCK). Then there was a burst of sound in it .... (we all know that we are afraid to eat food in disorder recently --!). Passers-by B can be anxious, covering his stomach, turning outside, stunned! After a while, passers-by took a cigarette, blew a whistle, and walked out of the toilet (Lock unlocked). Passers-by B hurried into the toilet, followed by a loud bang .....

Although this example is not harmonious, I believe you have understood the role of lock.

It is worth noting that: 1. The name of the locked object (the OBJ above) is generally declared as the object type. Be sure not to declare it as the value type. It doesn't matter what the object name is, you only need to comply with the object naming principles. 2. The object of the object type must be known as private and cannot be declared as public. Otherwise, the lock statement will be uncontrollable, this causes a series of problems. (Just like the example above: the dark night without five fingers (no electricity), passers-by B unlocks his belt, and is preparing to kneel down, one hand holding the PP of passers-by B, shouted: someone! --#.) 3. Too many codes should be in the critical section. If too much code is processed during lock and unlock, other threads waiting to run the code in the critical section will be blocked when a thread executes the code in the critical section, this may reduce the performance of the application. (Passers-by B will hate passers-by !)

Well, let's talk about it in a few minutes. Let's talk about the code and let's talk about the example of random withdrawals.

(1) create a Windows application named lockexample and put a ListBox and a button. The interface is as follows:

(2) Add a class: account. CS. The Code is as follows:

Class account {private object OBJ = new object (); int balance; random RD = new random (); form1 form1; Public Account (INT initial, form1 form1) {This. form1 = form1; this. balance = initial;} // <summary> // withdraws the specified amount. /// </Summary> /// <Param name = "amount"> the amount. </param> // <returns> </returns> private int withdraw (INT amount) {If (balance <0) {form1.addlistboxitem (" Balance "+ balance +" Brother, you think this is a credit card! Pay back the money! ") ;}// Read the lock (lockedobj) sentence to see what will happen lock (OBJ) {If (balance> = Amount) {string STR = thread. currentthread. name + "withdrawal ---"; STR + = string. format ("balance before withdrawal: {0,-6} withdrawal: {1,-6}", balance, amount); balance = balance-amount; STR + = "balance before withdrawal:" + balance; form1.addlistboxitem (STR); return amount;} else {return 0 ;}} public void dotransactions () {for (INT I = 0; I <100; I ++) {withdraw (Rd. next (1,100 ));}}}

(3) switch to the form1.cs code editing interface and write the code:

 

 Public     Partial     Class  Form1: Form
{
Public Form1 ()
{
Initializecomponent ();
}

Private Void Btnlock_click ( Object Sender, eventargs E)
{
Lblock. Items. Clear ();
Thread [] threads = New Thread [ 10 ];
Account ACC = New Account ( 1000 , This );
For ( Int I = 0 ; I < 10 ; I ++ )
{
Thread t = New Thread (Acc. dotransactions );
T. Name = " Thread " + I;
Threads [I] = T;
}

For ( Int I = 0 ; I < 10 ; I ++ )
{
Threads [I]. Start ();
}
}

Delegate Void Addlistboxitemdelegate ( String Str );
Public Void Addlistboxitem ( String Str)
{
If (Lblock. invokerequired)
{
Addlistboxitemdelegate d = Addlistboxitem;
Lblock. Invoke (D, STR );
}
Else
{
Lblock. Items. Add (STR );
}
}
}

(4) press <F5> compile and run, and click the "Start automatic random withdrawal" button to observe the possible content added to the ListBox after the thread is executed,

(5) use the lock (OBJ) StatementWatch out, Run the program again, observe the possible content added to the ListBox after the thread is executed,

In thread 6, the withdrawal balance is already 584, but in thread 7, the withdrawal balance is changed to 746. Obviously, the result is incorrect.

Now, let's take a look at the thread synchronization problem and its Solution to the synchronization problem. Here, I hope you can give more advice and make common progress.

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.