13

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.

SimpleButPerfect
  • 1,529
  • 2
  • 11
  • 20
  • which language are you using? – cpx Jan 19 '11 at 16:40
  • if you are asking the question: the answer is "no". Creating threads it's too easy, managing them and the data is harder. You can do even socket io in the same UI thread both in C and java. – bestsss Jan 21 '11 at 00:28

5 Answers5

14

In Threading in C# by Joseph Albahai has a nice section entitled Threading’s Uses and Misuses. It lists five common use cases for threading.

When To

Maintaining a responsive user interface

By running time-consuming tasks on a parallel “worker” thread, the main UI thread is free to continue processing keyboard and mouse events.

Making efficient use of an otherwise blocked CPU

Multithreading is useful when a thread is awaiting a response from another computer or piece of hardware. While one thread is blocked while performing the task, other threads can take advantage of the otherwise unburdened computer.

Parallel programming

Code that performs intensive calculations can execute faster on multicore or multiprocessor computers if the workload is shared among multiple threads in a “divide-and-conquer” strategy

Speculative execution

On multicore machines, you can sometimes improve performance by predicting something that might need to be done, and then doing it ahead of time. LINQPad uses this technique to speed up the creation of new queries. A variation is to run a number of different algorithms in parallel that all solve the same task. Whichever one finishes first “wins”—this is effective when you can’t know ahead of time which algorithm will execute fastest.

Allowing requests to be processed simultaneously

On a server, client requests can arrive concurrently and so need to be handled in parallel (the .NET Framework creates threads for this automatically if you use ASP.NET, WCF, Web Services, or Remoting). This can also be useful on a client (e.g., handling peer-to-peer networking—or even multiple requests from the user).

When not to

He goes on to caution the reader

With technologies such as ASP.NET and WCF, you may be unaware that multithreading is even taking place—unless you access shared data (perhaps via static fields) without appropriate locking, running afoul of thread safety.

Threads also come with strings attached. The biggest is that multithreading can increase complexity. Having lots of threads does not in and of itself create much complexity; it’s the interaction between threads (typically via shared data) that does. This applies whether or not the interaction is intentional, and can cause long development cycles and an ongoing susceptibility to intermittent and nonreproducible bugs. For this reason, it pays to keep interaction to a minimum, and to stick to simple and proven designs wherever possible. This article focuses largely on dealing with just these complexities; remove the interaction and there’s much less to say!

A good strategy is to encapsulate multithreading logic into reusable classes that can be independently examined and tested. The Framework itself offers many higher-level threading constructs, which we cover later.

Threading also incurs a resource and CPU cost in scheduling and switching threads (when there are more active threads than CPU cores)—and there’s also a creation/tear-down cost. Multithreading will not always speed up your application—it can even slow it down if used excessively or inappropriately. For example, when heavy disk I/O is involved, it can be faster to have a couple of worker threads run tasks in sequence than to have 10 threads executing at once. (In Signaling with Wait and Pulse, we describe how to implement a producer/consumer queue, which provides just this functionality.)

Conrad Frix
  • 51,984
  • 12
  • 96
  • 155
3

Multi-Threading has many, many aspects to think about. I recommend a tutorial: The Lesson: Concurrency from the Java Tutorial. Then you have to think about performance, but this is a special ability.

You will learn about the other problems when you face them.

Daniel
  • 27,718
  • 20
  • 89
  • 133
2
  • 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

Kalpit S.
  • 65
  • 7
1

Because all new generation CPU have multi-core architecture, i really suggest to develop ALWAYS multi thread application to exploit the full power of your CPU.

Whatever language you use, it's not important. When you approach to multi-thread application, in a general way, you must think as the software as a two or more software with a shared memory between him.

For first instance try to figure out which part of your software can be parallelized.

For example if you have a software generating a lot of data and then you need to write it on hard-disk, you can think to split the producer of the memory and the writer of the memory in two thread.

In this situation for example you have the first thread generating at FULL CPU speed as data as it's can create and the other thread writing the data on the disk at FULL DISK SPEED.

In this situation so, you have parallelized the cpu and the task of writing the data on disk and you have at the end a more fast application. - First thread will be assigned for example at the first core. - Second thread will be assigned at the second core.

So, because the disk is more slow of the CPU you don't have the bottleneck of the disk on your PRODUCER thread.

my 2 cents.

google this keyword: producer consumer algorithms

Roberto Martelloni
  • 587
  • 1
  • 5
  • 17
0

I use multithreading when i have a lot differnt types of tasks and priorities in an application.

An example could be if you need to log information to a database yet writing to the database takes too long and holds up the app. If u put the logging in another thread then that can happily sit there running queries without inteferring with the rest of the application.

Rich
  • 1