当前位置:编程学习 > C/C++ >>

Poco::ThreadPool

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

补充:软件开发 , C++ ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,