boost::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?
我看到了这个问题,而不是上面的代码使用了这个:
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();
}
那么有什么区别,哪个性能更好?会不会有内存泄漏?还是有另一种方法来创建一个简单的线程池?
我会很感激任何帮助。非常感谢。