C # three scenarios of thread synchronization,

Source: Internet
Author: User

C # three scenarios of thread synchronization,

C # has provided several useful class libraries such as BackgroundWorker, Thread, and Task. With these libraries, We can compile a multi-threaded application in minutes.

For example, there is a Winform. After you click the button, the data in the form will be exported to an outputexample file. The original code does not use multithreading technology, so when you click the button, the entire form becomes unresponsive. To solve this problem, you can use Task. Run () =>{... Export File Code });

The above Code seems simple, but it hides various crises. What if the data in the form is modified during the export process? What if multiple forms are exported to the same file at the same time?

After reading this series, you will be clear.

 

Some people know that thread synchronization has many means. mutex, moniter, seamphore, and event are classified into three categories, corresponding to three scenarios that require thread synchronization.

 

Scenario 1: The moukeng has a master

WhenOneWhen a resource is accessed by multiple threads at the same time, it may cause resource conflicts (especially when multiple write threads exist. In C #, Interlocked, lock, Moniter, SpinLock, ReadWriteLockSlim, and Mutex can be used to solve the problem.

For the differences between different solutions, click here.

 

Under what circumstances is scenario 1 considered?

When you design a class with static variables and I/O operations, you will encounter scenario 1. Because these resources are shared by multiple objects, when different threads access these resources at the same time, there may be contention.

When a class is designed as a singleton and contains instance variables, scenario 1 is also encountered. Because the instance variable belongs to this Singleton, when multiple threads manipulate this Singleton, the variable may be used for contention.

When a method in a class calls a thread to operate on an instance variable, it also encounters scenario 1.

 

Scenario 2: limited quantity, first come, first served

Scenario 1 emphasizes one-to-many scenarios. in scenario 2, the number of resources is not unique. Compared with scenario 1, scenario 2 focuses on the quantity limit. The classes used to meet this requirement include Semaphore and SemaphoreSlim.

For the differences between different solutions, click here.

 

Under what circumstances is scenario 2 considered?

When the number of concurrent operations on public resources is limited (such as the number of database connections and the number of IIS connections), this is considered scenario 2.

 

Scenario 3: I want you to change!

Scenario 3 focuses on the sequence in the thread execution process. The method used to ensure this sequence is through thread communication: ManualResetEventSlim, ManualResetEvent, and AutoResetEvent.

For the differences between different solutions, click here.

 

Under what circumstances is scenario 3 considered?

When two threads have successively dependent tasks, for example, the execution process of thread 2 depends on the execution result of thread 1, it is considered as scenario 3.

 

Unlimited use cases

The above solutions are not limited to a specific scenario. For example, AutoResetEvent can be used in scenario 3 or scenario 1. However, although AutoResetEvent can be used to meet the needs of scenario 1, it cannot use the thread communication capability of AutoResetEvent, at the same time, there are some additional restrictions (each thread must ensure that wait and set are used in pairs, otherwise a thread may be unlocked by another thread after the resource is locked ).

Lock (m) {//...} // is equivalent to autoResetEvent. WaitOne (); //... autoResetEvent. Set ();


Some friends also said that the lock solution in scenario 1 can be used to meet the needs of scenario 3.

AutoResetEvent autoReset = new AutoResetEvent (false); private void button#click (object sender, EventArgs e) {Task. run () => {autoReset. waitOne (); Console. writeLine ("Step 2") ;}); Thread. sleep (1000); // deliberately delay to ensure that the second thread is executed after the first thread. run () => {Console. writeLine ("Step 1"); autoReset. set ();});}

The final output result of the above example can be imagined. This example shows that the AutoResetEvent can easily guarantee the execution sequence of the two threads regardless of the actual execution sequence of the thread.

 

What if I use lock?

Private void button#click (object sender, EventArgs e) {Task. run () => {lock (s) {Console. writeLine ("Step 1") ;}}); Thread. sleep (1000); // manually ensure that the thread in step 2 must execute the Task after the thread in step 1. run () => {lock (s) {Console. writeLine ("Step 2 ");}});}

Although it can be implemented, additional code is required to manually ensure the execution sequence of the two threads.

 

How to determine the final use in so many solutions requires you to analyze the various scenarios of the project, and select the corresponding solution based on the actual situation, so that it will not be easy to use.

 

Summary

Through the introduction of this series of articles, we hope that you can have a concept about the scenarios that may be encountered in multithreading, so as not to be confused when faced with multithreading.

 

This article is from C # basic review: three scenarios of Thread Synchronization


A simple program of C language Bubble Sorting

Main ()
{
Int I, j, temp;
Int a [10];
For (I = 0; I <10; I ++)
Scanf ("% d,", & a [I]);
For (j = 0; j <= 9; j ++)
{For (I = 0; I <10-j; I ++)
If (a [I]> a [I + 1])
{Temp = a [I];
A [I] = a [I + 1];
A [I + 1] = temp ;}
}
For (I = 1; I <11; I ++)
Printf ("% 5d,", a [I]);
Printf ("\ n ");
}

--------------
Bubble Algorithm
Algorithm Analysis and Improvement of Bubble Sorting
The basic idea of exchanging sorting is to compare the keywords of the records to be sorted in pairs. If the order of the two records is the opposite, the two records are exchanged until there is no reverse order record.
The basic concepts of application exchange sorting include Bubble sorting and quick sorting.

Bubble Sorting

1. Sorting Method
Vertically arrange the sorted record array R [1. n]. Each record R is considered as a bubble with the weight of R. key. According to the principle that a Light Bubble cannot be under a heavy bubble, scan the array R from the bottom up: Any Light Bubble scanned to a violation of this principle will make it "float" up ". This is repeated until the last two bubbles are light and heavy.
(1) initial
R [1. n] is an unordered area.

(2) First scan
The weights of two adjacent bubbles are compared from the bottom of the unordered area to the top. If the light bubbles are found to be in the lower and severe bubbles, the positions of the two bubbles are exchanged. That is, compare (R [n], R [n-1]), (R [n-1], R [N-2]),…, (R [2], R [1]); for each pair of bubbles (R [j + 1], R [j]), if R [j + 1]. key <R [j]. key, then the contents of R [j + 1] and R [j] are exchanged.
When the first scan is complete, the "lightest" bubble floated to the top of the interval, that is, the record with the smallest keyword is placed on the highest position R [1.

(3) second scan
Scan R [2. n]. When scanning is completed, the "light" bubble floated to the R [2] position ......
Finally, the sequential area R [1. n] can be obtained through n-1 scanning.
Note:
During the I-trip scan, R [1 .. I-1] and R [I.. n] are the current sequential and disordered areas, respectively. The scan continues from the bottom of the unordered area to the top of the area. When scanning is completed, the shortest bubbles in the area float to the top position R. The result is that R [1. I] is changed to a new ordered area.

2. Bubble sorting process example
Bubble Sorting of files whose keyword sequence is 49 38 65 97 76 13 27 49

3. Sorting Algorithm
(1) Analysis
Because each sort adds a bubble to the ordered area, there are n-1 bubbles in the ordered area after N-1 sort, in the disordered area, the bubble weight is always greater than or equal to the bubble weight in the ordered area. Therefore, the entire Bubble sorting process requires at most n-1 sorting.
If no bubble position exchange is found in a sorting, it means that all bubbles in the unordered area to be sorted meet the principle of being light and heavy. Therefore, the Bubble sorting process can be terminated after this sorting. Therefore, in the following algorithm, a Boolean exchange is introduced, which is set to FALSE before each sort starts. If an exchange occurs during the sorting process, set it to TRUE. Check exchange at the end of sorting. If exchange has not occurred, terminate the algorithm and no longer perform the next sorting.

(2) specific algorithms
Void BubbleSort (SeqList R)
{// R (l. n) is the file to be sorted. It uses bottom-up scanning to perform Bubble Sorting on R.
Int I, j;
Boolean exchange; // exchange flag
For (I = 1; I <G id = "1">

A simple program of C language Bubble Sorting

Main ()
{
Int I, j, temp;
Int a [10];
For (I = 0; I <10; I ++)
Scanf ("% d,", & a [I]);
For (j = 0; j <= 9; j ++)
{For (I = 0; I <10-j; I ++)
If (a [I]> a [I + 1])
{Temp = a [I];
A [I] = a [I + 1];
A [I + 1] = temp ;}
}
For (I = 1; I <11; I ++)
Printf ("% 5d,", a [I]);
Printf ("\ n ");
}

--------------
Bubble Algorithm
Algorithm Analysis and Improvement of Bubble Sorting
The basic idea of exchanging sorting is to compare the keywords of the records to be sorted in pairs. If the order of the two records is the opposite, the two records are exchanged until there is no reverse order record.
The basic concepts of application exchange sorting include Bubble sorting and quick sorting.

Bubble Sorting

1. Sorting Method
Vertically arrange the sorted record array R [1. n]. Each record R is considered as a bubble with the weight of R. key. According to the principle that a Light Bubble cannot be under a heavy bubble, scan the array R from the bottom up: Any Light Bubble scanned to a violation of this principle will make it "float" up ". This is repeated until the last two bubbles are light and heavy.
(1) initial
R [1. n] is an unordered area.

(2) First scan
The weights of two adjacent bubbles are compared from the bottom of the unordered area to the top. If the light bubbles are found to be in the lower and severe bubbles, the positions of the two bubbles are exchanged. That is, compare (R [n], R [n-1]), (R [n-1], R [N-2]),…, (R [2], R [1]); for each pair of bubbles (R [j + 1], R [j]), if R [j + 1]. key <R [j]. key, then the contents of R [j + 1] and R [j] are exchanged.
When the first scan is complete, the "lightest" bubble floated to the top of the interval, that is, the record with the smallest keyword is placed on the highest position R [1.

(3) second scan
Scan R [2. n]. When scanning is completed, the "light" bubble floated to the R [2] position ......
Finally, the sequential area R [1. n] can be obtained through n-1 scanning.
Note:
During the I-trip scan, R [1 .. I-1] and R [I.. n] are the current sequential and disordered areas, respectively. The scan continues from the bottom of the unordered area to the top of the area. When scanning is completed, the shortest bubbles in the area float to the top position R. The result is that R [1. I] is changed to a new ordered area.

2. Bubble sorting process example
Bubble Sorting of files whose keyword sequence is 49 38 65 97 76 13 27 49

3. Sorting Algorithm
(1) Analysis
Because each sort adds a bubble to the ordered area, there are n-1 bubbles in the ordered area after N-1 sort, in the disordered area, the bubble weight is always greater than or equal to the bubble weight in the ordered area. Therefore, the entire Bubble sorting process requires at most n-1 sorting.
If no bubble position exchange is found in a sorting, it means that all bubbles in the unordered area to be sorted meet the principle of being light and heavy. Therefore, the Bubble sorting process can be terminated after this sorting. Therefore, in the following algorithm, a Boolean exchange is introduced, which is set to FALSE before each sort starts. If an exchange occurs during the sorting process, set it to TRUE. Check exchange at the end of sorting. If exchange has not occurred, terminate the algorithm and no longer perform the next sorting.

(2) specific algorithms
Void BubbleSort (SeqList R)
{// R (l. n) is the file to be sorted. It uses bottom-up scanning to perform Bubble Sorting on R.
Int I, j;
Boolean exchange; // exchange flag
For (I = 1; I <G id = "1">

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.