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?
i saw 这个问题 https://stackoverflow.com/questions/2659065/c-boost-thread-reusing-threads并使用以下代码代替上面的代码:
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();
}
那么有什么区别,哪一个性能更好呢?会不会出现内存泄漏?或者是否有另一种方法来创建简单的线程池?
我将不胜感激任何帮助。非常感谢。
一种选择是使用 boost asio。看一下线程池的配方:http://think-async.com/Asio/Recipes http://think-async.com/Asio/Recipes。然后,您可以使用 io_service 的 post 方法将事件发布到线程池。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)