Poco线程池

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 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); 

你可能感兴趣的:(linux线程编程相关,poco,框架学习)