Search This Blog

Monday, May 24, 2010

Simplest ThreadPool example Using C++

Hi guys,

I had very problem to find simple thread pooling program on net. So now I am presenting a simple example to explain ThreadPool in a very easy way. Hope you will like this.


What is ThreadPool?
Thread Pool is collection of Live, Reusable threads.

Why ThreadPool?
There are many situation where we can use ThreadPool. Consider a Client-Server application in which server has to respond to multiple client at same time. This means multitasking. Server will need a set of certain no. of threads which will do reply to client.
The big advantage of thread pool is that, it provides reusable thread. Though thread creation is very bulky process. It increases overhead. Suppose a new client send some data to server and Server has to respond. What will server do? It will create a new thread which will send data to client and then get killed or exited. Instead of creating thread on each client request we can keep collection of live thread. We will use any free thread which will send data to client. By that we will save a great overhead generated by creating threads multiple times.

ThreadPool Manager :
Hey we were talking about threadpool, now from where manager has come.
Hmmm, lets suppose I need some worker to do my work. I will go to a place(Array or Pool of threads) where I can find all workers. What I will do next? I will ask to each worker that are you free? Can you do work for me? Suppose a worst case when no workers are free then my effort for asking each worker will go waste.
Consider a person get hired to manage all information about worker like that who is free, ID of worker etc etc. I will directly go to Manager and will ask can u give me x worker for some work. Manager will check which worker is free now and if available he will assign worker to me.