Poco::ThreadPool提供線程池功能,減少線程的創建和銷毀所帶來的開銷,適合在服務器上應用。創建線程池時指定最少運行線程數和線程池的最大容量,若不指定則采用默認值,取2和16 。線程池的實現機制:有一部分線程始終處於運行狀態,但阻塞在Event的wait調用上,所以處於休眠狀態,開銷並不大。如果我們需要一個線程來運行一段代碼(在Poco中,用Runnable的子類表示一個target),則從線程池中去除一個線程,並將這段代碼賦給它,並觸發Event。然後線程就繼續運行了。
活動圖
demo
[cpp]
void ThreadPoolTest::testThreadPool()
{
ThreadPool pool(2, 3, 3);
assert (pool.allocated() == 2);
assert (pool.used() == 0);
assert (pool.capacity() == 3);
assert (pool.available() == 3);
pool.addCapacity(1);
assert (pool.allocated() == 2);
assert (pool.used() == 0);
assert (pool.capacity() == 4);
assert (pool.available() == 4);
RunnableAdapter<ThreadPoolTest> ra(*this, &ThreadPoolTest::hello);
pool.start(ra);
assert (pool.allocated() == 2);
assert (pool.used() == 1);
assert (pool.capacity() == 4);
assert (pool.available() == 3);
pool.start(ra);
assert (pool.allocated() == 2);
assert (pool.used() == 2);
assert (pool.capacity() == 4);
assert (pool.available() == 2);
pool.start(ra);
assert (pool.allocated() == 3);
assert (pool.used() == 3);
assert (pool.capacity() == 4);
assert (pool.available() == 1);
pool.start(ra);
assert (pool.allocated() == 4);
assert (pool.used() == 4);
assert (pool.capacity() == 4);
assert (pool.available() == 0);
}