Multithread counting how to keep the counting accurate method

  • 2020-04-01 02:45:44
  • OfStack

The singleton pattern in the design pattern is used first to prevent inconsistencies in the access space caused by multiple initializations of the object.

Add a lock at the count, the other thread count temporarily blocked, to ensure the correctness of the count.

If you want to count the real-time output in real time, you can lock the counting and output together, otherwise the counting and output results of different threads may not be processed in order.

Locking in this way ensures that the output is processed in order, but it costs some performance

The location of the lock in the code is important

This program will add three more operations, because this thread is not up to 200 times, but there must be a thread added for the first time, so make the judgment in add


CommonSigleton MyCounter =CommonSigleton.Instance;
  /// <summary>
  /// thread work
  /// </summary>
public void DoSomeWork()
{
    /// construct a display string
    string results = "";
    /// create a Sigleton instance
    System.Threading.Thread.Sleep(100);
    int i = 0;
    while (MyCounter.GetCounter() < 200)
    {
        //Ensuring that the count is consistent with the output, even if there is a time interval between the count and the output, locks the area to prevent other threads from operating
        lock (this)
        {
            /// start counting
            MyCounter.Add();
            System.Threading.Thread.Sleep(100);
            Thread thread = Thread.CurrentThread;
            results += " thread ";
            results += i++.ToString() + " -- > " + thread.Name + " ";
            results += " Current count: ";
            results += MyCounter.GetCounter().ToString();
            results += "n";
            Console.WriteLine(results);
            //Empty the display string
            results = "";
        }
    }
}
  public void StartMain()
  {
   Thread thread0 = Thread.CurrentThread; 

   thread0.Name = "Thread 0"; 

   Thread thread1 =new Thread(new ThreadStart(DoSomeWork)); 

   thread1.Name = "Thread 1"; 

   Thread thread2 =new Thread(new ThreadStart(DoSomeWork)); 

   thread2.Name = "Thread 2"; 

   Thread thread3 =new Thread(new ThreadStart(DoSomeWork)); 

   thread3.Name = "Thread 3";
            thread1.Start(); 

            thread2.Start(); 

            thread3.Start(); 

   /// thread 0 also performs the same work as other threads
   DoSomeWork(); 
  }
 }


Related articles: