boost :: thread类有一个默认构造函数,它给出了“Not-a-thread”,所以
是什么 boost::thread t1;
有益吗?我可以给它一个函数,以便稍后在代码中执行吗?
和另一个问题:
我正在尝试编写一个具有分阶段架构(SEDA)的小型服务器,每个阶段都有许多工作线程,并且这些阶段与事件队列连接。当我使用boost :: thread_group创建带有4个工作线程的池时,如下所示: (我已删除队列中的条件变量以进行清理,并假设队列的大小始终为4N。)
boost::thread_group threads;
while(!event_queue.empty())
{
for(int i = 0; i < 4; ++i)
{
threads.create_thread(event_queue.front());
event_queue.pop();
}
threads.join_all();
}
thread_group的规模不断扩大。组中已完成的线程会发生什么?如何重用这些线程并将thread_group大小保持为4?
我看到this question而不是上面的代码使用了这个:
std::vector<boost::shared_ptr<boost::thread>> threads;
while(!event_queue.empty())
{
for(int i = 0; i < 4; ++i)
{
boost::shared_ptr<boost::thread>
thread(new boost::thread(event_queue.front());
event_queue.pop();
threads.push_back(thread);
}
for(int i = 0; i < 4; ++i)
threads[i]->join();
threads.clear();
}
那么有什么不同,哪一个有更好的表现?会有内存泄漏吗?还是有另一种方法来创建一个简单的线程池?
我很感激任何帮助。非常感谢你。
答案 0 :(得分:2)
一种选择是使用boost asio。看一下线程池的配方:http://think-async.com/Asio/Recipes。然后使用io_service的post方法将事件发布到线程池。