Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

To multi-thread or not to multi-thread!

That is the question!

When is multi-threading an application a must, and what to consider in multi-threading in general?

It would be greatly appreciated if an example is posted along with the explanation.

Thanks.

PS. I tried checking all the possible questions before posting, if this question is simply another duplicate, please close it.

like image 205
SimpleButPerfect Avatar asked Jan 19 '11 16:01

SimpleButPerfect


1 Answers

  • Multi threading is a concept where we divide a process into many independent sub processes(called a thread), however they may depend on a single resource such as data resource in that case they need to access it exclusively.
  • Threads are needed when we want the processor to be busy with some sub process(thread) while other sub processes are waiting for IO or any other resources. However threads can run parallel only if the CPU is multi-core otherwise they generally work on time-sharing concept(one sub-process executes for some time(time quantum) and then other).

For example we can understand multi threading by the process of billing at billing counter of a shop or a MALL. so only one counter is a single threaded process and multi counters is a multi threaded process.so in multi threading the whole process of billing is divided into many sub processes by many billing counters (multiple threads) aim at doing the billing job.

So for implementation of threads we have following example:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading;

namespace ThredsRND
{
    public abstract class TaskRequest
    {
    }
    public abstract class TaskManager<T> where T : TaskRequest
    {
        protected Queue<T> Requests = new Queue<T>();
        private int NumberOfThreads { get; set; }

        public void Run(int _numberOfThreads)
        {
            NumberOfThreads = _numberOfThreads;
            CreateTasks();
            List<Thread> threads = new List<Thread>();

            if (NumberOfThreads <= 0)
                NumberOfThreads = 1;

            for (int i = 0; i < NumberOfThreads; i++)
            {
                Thread th = new Thread(_ExecuteThread);
                th.Start();
                threads.Add(th);
            }

            threads.ForEach(x => x.Join());
        }

        private object _key = new object();

        private void _ExecuteThread()
        {
            while (true)
            {
                T request = null;
                lock (_key)
                {
                    if (Requests.Count > 0)
                        request = Requests.Dequeue();
                }

                if (request != null)
                {
                    Console.WriteLine("THREAD:" + Thread.CurrentThread.ManagedThreadId);
                    ExecuteTask(request);
                }
                else return;
            }
        }

        public abstract void CreateTasks();
        public abstract void ExecuteTask(T request);

    }
}

now this taskManager class will have to be inherited and its abstract functions need to be defined.

for example:

 class SimpleReportRequest:TaskRequest
{
    public int Start { get; set; }
    public int End { get; set; }
}
class SimpleReportCreator : TaskManager<SimpleReportRequest>
{
    public override void CreateTasks()
    {
        for (int i = 1; i <= 100; i++)
        {
            SimpleReportRequest req = new SimpleReportRequest();
            req.Start = i;
            req.End = i+1;
            Requests.Enqueue(req);
        }
    }



public override void ExecuteTask(SimpleReportRequest request)
    {//what each process of this type should doo..  

}

The Main Program;

 static void Main(string[] args)
    {
        SimpleReportCreator creator = new SimpleReportCreator();
        DateTime start = DateTime.Now;
        Console.WriteLine("started at: "+ start);
        creator.Run(100);
        DateTime end = DateTime.Now;
        Console.WriteLine("Total Time taken with threads: " +(end-start));

        Console.WriteLine("ALL END");
        Console.ReadLine();

        return;}

HOPE THIS POST IS VERY MUCH USEFUL

like image 72
Kalpit S. Avatar answered Sep 30 '22 20:09

Kalpit S.