On 04.03.17 07.35, kushal bhattacharya wrote:
> Suppose i am running multiple parrallel threads in my program.So can i reuse the idle parrallel threads in order to to do some new task for a different context.
This is possible. The concept is usually called ->"thread pool". Tasks
from a TODO queue are scheduled to free threads from the pool and the
thread is put back into the queue if there is nothing to do instead of
discarding it.
This concept if often implemented by web servers.
> ( I am assuming that the previously created parrallel threads are
mostly in idle state when there is no event occuring on it).
Well, "mostly" is not sufficient in any way. To get this concept working
you need /know/ whether there is something to do. An important property
is that the tasks must not block for longer e.g. at I/O operations while
the thread is still allocated from the pool.
This can be handled by using ->"asynchronous I/O". Many operating
systems provide APIs for asynchronous I/O. The concept is to release the
thread while waiting for I/O and allocate a new one from the pool as
soon as the operating system notifies that the I/O has completed.
However, in practice it depends on your platform and the number and
latency of the concurrent I/O operations whether this is a good idea.
I have worked on platforms where "start thread" was a machine
instruction which took only half a dozen clock cycles. Managing a thread
pool is by far more expensive than starting additional threads in this case.
And using asynchronous I/O is a major change in the design of the
program flow.
Marcel