Multithreading refersProgramContains multiple execution streams, that is, a program can run multiple different threads to execute different tasks at the same time, that is to say, a single program is allowed to create multiple parallel threads to complete their respective tasks. CPU utilization can be improved. In a multi-threaded program, when a thread has to wait, the CPU can run other threads instead of waiting, which greatly improves the program efficiency.
Example:
In an example, the function add is used to increase the data and delete is used to reduce the data. If multiple threads operate on the data at the same time, the increase and decrease operations will occur, in this way, when the increase is not completed, only the data reduction operation is completed.
Example:
Private int COUNT = 12; Public void add () {console. writeline ("before the add method" + count); count + = 2; console. writeline ("add method" + count);} public void Delete () {console. writeline ("before the delete method" + count); count-= 2; console. writeline ("after Delete" + count);} private void button5_click (Object sender, eventargs e) {// thread synchronization thread [] T = new thread [10]; for (INT I = 0; I <t. length; I ++) {if (I % 2 = 0) {T [I] = new thread (New threadstart (ADD ));} else {T [I] = new thread (New threadstart (delete) ;}}for (INT I = 0; I <t. length; I ++) {T [I]. start ();}}
AboveCodeData is not synchronized. The texture display is as follows:
Common classes used in C # To implement thread synchronization include the following:
1. mutex class (mutex), monitor class, and lock Method
2. manualresetevent class and autoresetevent class (both are derived from the eventwaithandle class)
3. readerwriterlock class
C # provides a keyword lock, which defines a piece of code as a critical section. A mutex section allows only one thread to enter the execution at a time point, other threads must wait.
Here we only use the lock method:
After this modification, you only need to modify the called method. There is no difference between the online creation and execution:
Private Static object mylock = new object (); Private int COUNT = 12; Public void add () {lock (mylock) {console. writeline ("before the add method" + count); count + = 2; console. writeline ("add method" + count) ;}} public void Delete () {lock (mylock) {console. writeline ("before the delete method" + count); count-= 2; console. writeline ("after the delete method" + count );}}