Multithreading Series 1 and multithreading Series

Source: Internet
Author: User

Multithreading Series 1 and multithreading Series

Thread, process, and link I will not be in BB anymore.

As for threads, I believe everyone knows a lot about them. Here I just want to express my understanding and understanding of threads. If any, please point out.

1 class Program 2 {3 static void Main (string [] args) 4 {5 Thread t = new Thread (Runing); 6 t. name = "test thread"; 7 t. start (); 8 Console. readLine (); 9} 10 11 static void Runing () 12 {13 Console. writeLine (Thread. currentThread. name + ":" + DateTime. now. toString (); 14} 15}

The above code is certainly familiar to everyone ~!

Next, let's modify the program to complete the single-thread processing task. We know that many times, when our program is designed with multiple clients or multiple request sources and concurrent requests come, we need to process tasks in the queue, such as seckilling and placing orders.

Public class MyThread1 {// notify one or more threads that an event has occurred in the waiting thread ManualResetEvent mre = new ManualResetEvent (false); // The server running identity bool isRuning = true; // thread-safe queue System. collections. concurrent. concurrentQueue <string> cqueue = new System. collections. concurrent. concurrentQueue <string> (); public MyThread1 () {Thread t = new Thread (RunTest); t. name = "I'm a test thread"; t. start () ;}// simulate the new task public void add (int I) {// add the task to the queue cqueue. enqueue ("" + I); // wake up all related pending threads mre. set ();} static void Main (string [] args) {MyThread1 p = new MyThread1 (); for (int I = 0; I <10; I ++) {p. add (I);} Console. readLine ();} void RunTest () {// main cyclic server running identity while (isRuning) {// if it is null, continue waiting for the server running identity while (cqueue. isEmpty & isRuning) {Console. writeLine (DateTime. now. toString ("HH: mm: ss: ffff") + ":" + Thread. currentThread. name + "sleep"); // reset the thread pause state mre. reset (); // this operation is performed so that the server needs to stop the operation, // If the Thread of the call Thread is stopped. abort () will lead to the loss of mre for processing queue tasks. waitOne (2000);} string ret; // retrieves the queue task if (cqueue. tryDequeue (out ret) {// test the output task Console. writeLine (DateTime. now. toString ("HH: mm: ss: ffff") + ":" + Thread. currentThread. name + "" + ret );}}}}

Use add to implement the concurrent order RunTest () method to implement the processing logic,

Here, ManualResetEvent is used to suspend and wake up a thread. When the queue is empty, the thread automatically enters the pending state. When a new task or add operation is available, the suspended thread is directly awakened. Enter the processing status immediately.

Why do I use ManualResetEvent to notify the thread? I will not explain it here. If you are interested, you can use Baidu ~!

To avoid the failure of subsequent queue operations caused by calling Thread. Abort () when the server needs to be shut down, the bool variable of isRuning is added to realize whether the Thread continues to run.

 

The above functions are always similar to processing orders and require single-thread queue processing. Analyze the requirements by yourself ~~!

With the above single-thread processing queue requirements, we may think that there will naturally be a multi-thread processing queue in the program running.

For example, we record the logs (for example, if you like log4Net or log4J very much, Please bypass). We need to submit the log records, but we do not want this operation to delay the normal operation of the program, in addition, record programs such as logs cannot be processed by a single thread,

If the log is recorded wildly, it will inevitably lead to the problem of memory overflow caused by not timely processing.

So modify the program again.

1 public class MyThread3 2 {3 // notify one or more threads that an event has occurred. 4 ManualResetEvent mre = new ManualResetEvent (false ); 5 // server running ID 6 bool isRuning = true; 7 // thread-safe queue 8 System. collections. concurrent. concurrentQueue <string> cqueue = new System. collections. concurrent. concurrentQueue <string> (); 9 // counting memory 10 Dictionary <string, int> cdic = new Dictionary <string, int> (); 11 12 public MyThread3 () 13 {14 List <Thread> ts = new List <Thread> (); 15 for (int I = 0; I <4; I ++) 16 {17 Thread t = new Thread (RunTest); 18 t. name = "I Am a thread (" + I + ")"; 19 cdic [t. name] = 0; 20 t. start (); 21 ts. add (t); 22} 23} 24 25 // simulate new task 26 public void Add () 27 {28 Thread t1 = new Thread (() => 29 {30 for (int I = 0; I <40; I ++) 31 {32 // Add the task to the queue 33 cqueue. enqueue ("logging" + I); 34 // wake up all related suspended threads 35 mre. set (); 36} 37 38}); 39 t1.Start (); 40 41} 42 43 // output counter 44 public override string ToString () 45 {46 foreach (var item in cdic) 47 {48 Console. writeLine (item. key + "count" + item. value); 49} 50 return ""; 51} 52 53 54 static void Main (string [] args) 55 {56 MyThread3 p = new MyThread3 (); 57 p. add (); 58 Console. readLine (); 59 p. toString (); 60 Console. writeLine (); 61 Console. readLine (); 62} 63 64 void RunTest () 65 {66 // master cyclic server running ID 67 while (isRuning) 68 {69 // if it is null, continue to wait for the server running ID 70 while (cqueue. isEmpty & isRuning) 71 {72 // reset the thread pause status 73 mre. reset (); 74 // this operation is performed so that the server needs to stop the operation, 75 // If the Thread of the call Thread is stopped. abort () will cause loss of processing queue tasks 76 mre. waitOne (2000); 77 Console. writeLine (DateTime. now. toString ("HH: mm: ss: ffff") + ":" + Thread. currentThread. name + "sleep"); 78} 79 string ret; 80 // retrieve queue task 81 if (cqueue. tryDequeue (out ret) 82 {83 // test the output task 84 Console. writeLine (DateTime. now. toString ("HH: mm: ss: ffff") + ":" + Thread. currentThread. name + "" + ret); 85 // Add a task counter. To view the count of the last Thread-executed task 86 cdic [Thread. currentThread. name] = cdic [Thread. currentThread. name] + 1; 87} 88} 89} 90}

Output

Multiple Threads process log records, pause threads in idle time, and wake up tasks to ensure that the logs can be processed in real time without wasting resources ~!

The first time I wrote a blog, my language skills were poor. Let's take a look at the program code and comments!

For more information.

 

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.