贴一段代码上的注释,google translate
A thread pool always keeps a number of threads running, ready to accept work.
Creating and starting a threads can impose a significant runtime overhead to an application.
A thread pool helps to improve the performance of an application by reducing the number of threads that have to be created (and destroyed again).
Threads in a thread pool are re-used once they become available again.
The thread pool always keeps a minimum number of threads running.
If the demans for threads increases, additional threads are created.
Once the demand for threads sinks again, no-longer used threads are stopped and removed from the pool.
线程池始终保持许多线程在运行,随时可以接受工作。
创建和启动线程可能会给应用程序带来大量的运行时开销。
线程池通过减少必须创建(并再次销毁)的线程数来帮助提高应用程序的性能。
线程池中的线程一旦再次可用就可以重新使用。
线程池始终保持最小数量的线程在运行。
如果线程需求增加,则会创建其他线程。
一旦对线程的需求再次下降,不再使用的线程将停止并从池中删除。
#include "Poco/Thread.h"
#include "Poco/Runnable.h"
#include "Poco/Timestamp.h"
#include <ctime>
#include <cmath> //使用其中的 pow 函数
#include "Poco/ThreadPool.h"
#include "Poco/RunnableAdapter.h"
using Poco::ThreadPool;
using Poco::Timestamp;
void HaveToDo()
{
for (int i = 0; i < 1000; ++i)
pow(1973, 878979); // wait a bit
}
class HelloRunnable: public Poco::Runnable
{
virtual void run()
{
HaveToDo();
}
};
int main(int argc, char** argv)
{
long int time_by=0;
Timestamp now; // the current date and time
for (int replay = 10000; replay > 0; replay--)
{
now.update();
HaveToDo();
Timestamp::TimeDiff diff = now.elapsed(); // how long did it take?
time_by += diff;
}
printf("normal: %ldus\n",time_by/100);
time_by=0;
HelloRunnable runnable;
for (int replay = 10000; replay > 0; replay--)
{
now.update();
Poco::Thread thread;
thread.start(runnable);
thread.join();
Timestamp::TimeDiff diff = now.elapsed(); // how long did it take?
time_by += diff;
}
printf("middle: %ldus\n",time_by/100);
time_by=0;
ThreadPool pool(70,80,10);
now.update();
for (int replay = 10000; replay > 0; replay--)
{
while(pool.available()==0);
pool.start(runnable);
//printf("available: %d %d\n",pool.available(), replay);
}
pool.joinAll();
Timestamp::TimeDiff diff = now.elapsed(); // how long did it take?
printf("last: %ldus\n",time_by/100);
return 0;
}