Data Processing Speed: ThreadPool or Thread Loop with Event?

I need to process data in another thread. There are two ways to do this:

  • Using a thread loop waiting for an event:

    AutoResetEvent e = new AutoResetEvent(false)
    Thread t = new Thread(delegate
    {
      while(true)
      {
        e.WaitOne();
        // process data
      }
    };)
    
    void OnProgramStarted() // one time
    {
      t.Start();
    }
    
    void OnDataReceived()
    {
      // put data to queue
      e.Set();
    }
    
  • Using thread pool:

    void ProcessData(object state)
    {
      // process data
    }
    
    void OnDataReceived()
    {
      // put data to queue
      ThreadPool.QueueUserWorkItem(ProcessData);
    }
    

Which way will be faster?
These tests give mixed results.

My control code:

using System;
using System.Diagnostics;
using System.Threading;

namespace t_event_tpool
{
  class Program
  {
    const int t = 1000000;

    static Stopwatch sw = new Stopwatch();
    static int q1, q2;


    static AutoResetEvent e1 = new AutoResetEvent(false);
    static AutoResetEvent done1 = new AutoResetEvent(false);

    static Thread thread = new Thread(ThreadProc);
    static void ThreadProc(object state)
    {
      while(true)
      {
        e1.WaitOne();
        q1++;
        done1.Set();
      }
    }


    static AutoResetEvent done2 = new AutoResetEvent(false);

    static void PoolProc(object state)
    {
      q2++;
      done2.Set();
    }


    static void TestA()
    {
      sw.Restart();
      for(int i = 0; i < t; i++)
      {
        e1.Set();
        done1.WaitOne();
      }
      sw.Stop();
      Console.WriteLine("a " + sw.ElapsedMilliseconds + "\t" + q1);
    }

    static void TestB()
    {
      sw.Restart();
      for(int i = 0; i < t; i++)
      {
        ThreadPool.QueueUserWorkItem(PoolProc, i);
        done2.WaitOne();
      }
      sw.Stop();
      Console.WriteLine("b " + sw.ElapsedMilliseconds + "\t" + q2);
    }



    static void Main(string[] args)
    {
      thread.IsBackground = true;
      thread.Start();

      TestA();
      TestB();

      TestA();
      TestB();

      TestA();
      TestB();
    }
  }
}

With a low processor load (without other applications) TestB is 2 times faster than TestA. With high CPU utilization by other processes, TestA is faster than TestB.

+4
source share
1 answer

. . , , , . , 0,1 , , . .

: , , , . . . , Disruptor.

+1

Source: https://habr.com/ru/post/1544101/


All Articles