How would one implement a threadpool? I've been reading on wikipedia for "threadpool" but I still can't figure out what one should do to solve this question (possibly because I didn't quite understand what a threadpool is in simple terms).
Can someone explain me in plain english what a threadpool is and how would one answer this question?
Best Answer
A thread pool is a group of pre-instantiated, idle threads which stand ready to be given work. These are preferred over instantiating new threads for each task when there is a large number of short tasks to be done rather than a small number of long ones. This prevents having to incur the overhead of creating a thread a large number of times.
Implementation will vary by environment, but in simplified terms, you need the following:
Task
with anexecute()
method that does the work and then returns.When the thread pool is created, it will either instantiate a certain number of threads to make available or create new ones as needed depending on the needs of the implementation.
When the pool is handed a
Task
, it takes a thread from the container (or waits for one to become available if the container is empty), hands it aTask
, and meets the barrier. This causes the idle thread to resume execution, invoking theexecute()
method of theTask
it was given. Once execution is complete, the thread hands itself back to the pool to be put into the container for re-use and then meets its barrier, putting itself to sleep until the cycle repeats.