Saturday, July 26, 2008

MultiThreading

Multithreading is a technique that can be used to perform time consuming tasks in a separate additional thread other than the main application thread.

When you, for example, have a time-consuming function, you may need to call this function as a response of a button click. Now, instead of freezing all your application waiting for this function to return / to finish, you can create a new thread and assign this function to. When you do this, your application interface will not be blocked and you can use it to perform other tasks. At the same time, your time-consuming task is being carried out in the background.

You can think of it as the two threads: the main one, and the newly created one. Both are running in parallel, and this improves the performance and responsiveness of your application.

Advantages and Disadvantages of Using Multithreading

Despite improving your application's performance, and avoiding unresponsive user interface, multithreading has the following disadvantages:

  • There is a runtime overhead associated with creating and destroying threads. When your application creates and destroys threads frequently, this overhead affects the overall application performance.
  • Having too many threads running at the same time decreases the performance of your entire system. This is because your system is attempting to give each thread a time slot to operate inside.
  • You should design your application well when you are going to use multithreading, or otherwise your application will be difficult to maintain and extend.
  • You should be careful when you implement a multithreading application, because threading bugs are difficult to debug and resolve.

Notes:

  • Each time a thread is created, a certain amount of memory is consumed to hold this thread context information. Hence, the number of threads that can be created is limited by the amount of available memory.

  • More threads does not mean a faster responsive application, instead it can decrease the performance of your application.

No comments: