Why learn multithreading?

  • January 21, 2010 is the deadline for applying for the 2010 civil servant exam in a city. The registration period, which was scheduled to close at 5 p.m. yesterday, was delayed to 11 a.m. today because the Beijing personnel examination website for registration was down from 2 p.m.
  • At 5pm on March 11, 2011 (9am on March 12, Beijing time), Apple unveiled the new generation of tablet computer product iPad 2, equipped with a5.1ghz dual-core processor, which means that tablets and laptops have entered the “multi-core era”.
  • On June 18 of the same year, jingdong, a famous B2C company in China, held a “grand” large-scale promotion activity on the occasion of its anniversary celebration. As a result, the purchase rush followed, and the orders were crowded and jingdong’s deadline was temporarily cancelled. Yesterday consumer reflection, because of the large number of hits, 18 morning Jingdong mall website once paralyzed. One customer said, “I have been unable to log on to JINGdong Mall since 1 a.m. on Monday.” Liu qiangdong also said that the server runs slowly because the traffic repeatedly exceeds 4 GIGABytes. “The ‘618’ campaign was extremely popular and users placed orders at an unprecedented speed. As a result, the display of orders placed by some users was delayed, and users were unable to check their orders in myJingdong for a period of time,” jingdong said in a statement on its website yesterday. We apologize for any inconvenience this may have caused you.”
  • On May 5th, 2015, WHEN I logged into hyacinth online mall, I found that there was only one button “register an account to get more discounts” on the homepage in addition to advertisements and related messages. There was no product display, no product search, no online ordering, and even no button to enter the mall. Hyacinth Nansha cross-border direct purchase experience center related person said, this is mainly because of the number of reservations, as of May Day, the number of reservations has exceeded 100,000, too many people frequently log in, resulting in the shop server paralysis, technical personnel are still trying to repair. The person in charge of the introduction, the experience center’s website is currently being debugged, “the current role of the website is mainly to the public booking and advance registration, through the network of registered citizens do not need to verify the id card and other information, can improve the purchase efficiency.”

Here are some examples to introduce you to multithreading and why you should learn about it.

Let me write v out front

There are only two kinds of bosses, good and bad. Good bosses talk about money, bad bosses talk about dreams.

V Simulation scenario

Suppose there is a monitor in the background that monitors orders and can find orders and process them. Each time (1 time /S), 1,000 orders can be processed. Instructions need to be sent to the warehouse system to make them responsible for delivery and delivery. So let’s write an EmulationSystem

JobHelper because we’re just simulating an environment, so it looks like this.

//------------------------------------------------------------------------------ // <copyright file="JobHelper.cs" Company ="CNBlogs Corporation" owner=" CNBlogs Corporation" owner=" CNBlogs Corporation" >  http://www.cnblogs.com/toutou/ // </copyright> //------------------------------------------------------------------------------ namespace CNBlogs.Common.Shared { using  System.Threading; /// <summary> /// Job helper /// </summary> public class JobHelper { /// <summary> /// Get job total count /// </summary> // <returns></returns> public int GetJobCount() {// Our focus is on multithreading, so we simulate 1000 orders at a time, and simulate, so we don't care about anything else. As long as the order quantity. return 1000; } /// <summary> /// Submit job /// </summary> /// <param name="jobId">For job id</param> /// <returns>Submit job Status </returns> public bool SubmitJob(int jobId) {// Assume that it takes 1 second to send a task to the background for each order and that thread.sleep (1000) can be sent successfully for each order; return true; }}}Copy the code

We have finished the background, now we need to get the order information, submit these orders to the warehouse.

V Actual combat exercise

Given this background, there are a number of ways we can deal with it.

  • Traditional methods:

    (Enable mindless mode: not using multi-threading)

    Code body:

    //------------------------------------------------------------------------------ // <copyright file="Runner.cs" Company ="CNBlogs Corporation" owner=" CNBlogs Corporation" owner=" CNBlogs Corporation" >  http://www.cnblogs.com/toutou/ // </copyright> //------------------------------------------------------------------------------ namespace CNBlogs.EmulationSystem { using System; using System.Threading; using CNBlogs.Common.Shared; class Runner { /// <summary> /// Job helper /// </summary> private static JobHelper jobHelper = new JobHelper(); /// <summary> /// Runner lock /// </summary> private static Mutex mutex; DateTime paddingTime = datetime.now.tolocalTime (); static void Main(string[] args) {DateTime paddingTime = datetime.now.tolocalTime (); int orderCount = jobHelper.GetJobCount(); // Initialize a new instance of the Mutex class with a Boolean value indicating whether the calling thread should have initial ownership of the Mutex. // The current process can only be started once mutex = new mutex (false, "CNBlogs.EmulationSystem"); if (! mutex.WaitOne(0, false)) { Console.Out.WriteLine("Monitor already running..." ); return; } for (int i = 0; i < orderCount; I ++) {// Suppose I is job id jobhelper.submitJob (I); } // completeTime completeTime = datetime.now.tolocalTime (); var minutes = (completeTime - paddingTime).TotalSeconds; Format(" Processing {0} orders, take {1} seconds ", orderCount, minutes)); }}}Copy the code

    Code effect:

    PS: Nowadays, these e-commerce companies are always holding anniversary stores to celebrate double 11 and double 12, so that we ordinary people all flock to each other. Obviously, if we use the traditional method, although there is no mistake, the boss will definitely ask you for tea. In the multi – nuclear age, this method can only be used for iron. So this method is absolutely not desirable.

  • Methods the Task:

    If you are not familiar with the Task, you can solve the puzzle here.

    Code body:

    //------------------------------------------------------------------------------ // <copyright file="Runner.cs" Company ="CNBlogs Corporation" owner=" CNBlogs Corporation" owner=" CNBlogs Corporation" >  http://www.cnblogs.com/toutou/ // </copyright> //------------------------------------------------------------------------------ namespace CNBlogs.EmulationSystem { using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using CNBlogs.Common.Shared; class Runner { /// <summary> /// Job helper /// </summary> private static JobHelper jobHelper = new JobHelper(); /// <summary> /// Runner lock /// </summary> private static Mutex mutex; DateTime paddingTime = datetime.now.tolocalTime (); static void Main(string[] args) {DateTime paddingTime = datetime.now.tolocalTime (); int orderCount = jobHelper.GetJobCount(); // Initialize a new instance of the Mutex class with a Boolean value indicating whether the calling thread should have initial ownership of the Mutex. // The current process can only be started once mutex = new mutex (false, "CNBlogs.EmulationSystem"); if (! mutex.WaitOne(0, false)) { Console.Out.WriteLine("Monitor already running..." ); return; } var taskList = new List<Task>(); for (int i = 0; i < orderCount; i++) { int temp=i; Tasklist.add (task.factory.startNew (() => {// If I is job ID jobhelper.submitJob (temp); })); } task.waitall (tasklist.toarray ()); DateTime completeTime = datetime.now.tolocalTime (); var minutes = (completeTime - paddingTime).TotalSeconds; Format("Complete: {0}, cost {1} s", orderCount, minutes); }}}Copy the code

    Code effect:

    I believe that from the two demos with and without tasks, we can clearly find the charm of multi-threading to deal with these frequent interactions. You’ll love it. It does increase efficiency. The problem, however, is that the number and size of multiple threads in a process is required (depending on the server configuration), not something we can exploit arbitrarily. If there are too many orders and we don’t control the task, it will cause hate. Tasks need control.

  • Semaphore:

    If you are not familiar with Semaphore, you can solve the heart riddle here.

    Code body:

    //------------------------------------------------------------------------------ // <copyright file="Runner.cs" Company ="CNBlogs Corporation" owner=" CNBlogs Corporation" owner=" CNBlogs Corporation" >  http://www.cnblogs.com/toutou/ // </copyright> //------------------------------------------------------------------------------ namespace CNBlogs.EmulationSystem { using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using CNBlogs.Common.Shared; class Runner { /// <summary> /// Job helper /// </summary> private static JobHelper jobHelper = new JobHelper(); /// <summary> /// The locker used to lock the semaphore and thread. /// </summary> private static object lockerObj = new  object(); /// <summary> /// The semaphore limit the thread number of get latest test info /// </summary> private static Semaphore semaphoreLimit; /// <summary> /// Runner lock /// </summary> private static Mutex mutex; DateTime paddingTime = datetime.now.tolocalTime (); static void Main(string[] args) {DateTime paddingTime = datetime.now.tolocalTime (); int orderCount = jobHelper.GetJobCount(); // Initialize a new instance of the Mutex class with a Boolean value indicating whether the calling thread should have initial ownership of the Mutex. // The current process can only be started once mutex = new mutex (false, "CNBlogs.EmulationSystem"); if (! mutex.WaitOne(0, false)) { Console.Out.WriteLine("Monitor already running..." ); return; Int maxProcNumber = 500; Using (semaphoreLimit = new Semaphore(0, maxProcNumber)) {// Exit the Semaphore a specified number of times and return the previous count. semaphoreLimit.Release(maxProcNumber); var taskList = new List<Task>(); for (int i = 0; i < orderCount; i++) { int temp=i; Lock (lockerObj) //{semaphorelimite.waitone (); semaphorelimite.waitone (); Tasklist.add (task.factory.startNew (() => {// If I is job ID jobhelper.submitJob (temp); Exit the semaphore and return the previous count. semaphoreLimit.Release(); })); Task.waitall (tasklist.toarray ()); } // completeTime completeTime = datetime.now.tolocalTime (); var minutes = (completeTime - paddingTime).TotalSeconds; Format("Complete: {0}, cost {1} s", orderCount, minutes); }}}Copy the code

    Code effect:

V Blog Summary

Multithreading is a long way off…

 

About the author: Focus on basic platform project development. If you have any questions or suggestions, please feel free to comment! Copyright notice: The copyright of this article belongs to the author and the blog garden, welcome to reprint, but without the consent of the author must retain this statement, and give the original text link in a prominent place on the page of the article. For the record: all comments and messages will be answered as soon as possible. You are welcome to correct your mistakes and make progress together. Or direct private message I support the blogger: if you think the article is helpful to you, you can click on the lower right corner of the article [recommendation]. Your encouragement is the author to adhere to the original and continuous writing of the biggest power! \