Thread Pool


Thread pool implemented in CThreadPool, a pool of iPoolSize = 2 threads running all the time, taking task = worker function from mQueue

Why use pool:
to avoid cost of thread creation and destruction.
better tracking: like max number of threads.

How to use it: see TestThreadPool()
fuFunctor = myPool.Push(myFunctor, ‘b’); //’b’ is parameters of the functor/function
fuFunctor is the future, fuFunctor.get(), which verly likely calls .wait internally; gives return value and indicates the function is done.

APIs used: :vector of :thread-s, queue of tasks=function, packaged_task, :condition_variable, :mutex

Implementation:
How a task is added: see .Push()
caller passes in function ptr and parameters
bind() package them to form a packaged_task, which exposes a :future to be returned to caller.
after mQueue.emplace this this task, mCv.notify_one

How is return value set: when caller’s function calls return 2; 2 is tranfered to fuFunctor and cause fuFunctor.get to exit, all handled by packaged_task
to exit: return statement in func cause packaged_task to set future.
The workers: 2 instance of funcThread running, each: cv.wait, take one from mQueue and run the task.
ctor: fill pool by starting all threads

Notes: packaged_task is higher level than :thread as it automatically set future, while with :thread, we have to manually pass and set future.
result_of replaced by invoke_result

Download: http://riowing.net/p/wp/Threadpool.cpp