【问题标题】:boost::thread and creating a pool of them!boost::thread 并创建一个池!
【发布时间】:2011-03-28 08:50:33
【问题描述】:

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?

我看到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();
}

那么有什么区别,哪个性能更好?会不会有内存泄漏?还是有其他方法可以创建一个简单的线程池?

如果有任何帮助,我将不胜感激。非常感谢。

【问题讨论】:

    标签: boost-thread


    【解决方案1】:

    一种选择是使用 boost asio。看看线程池的配方:http://think-async.com/Asio/Recipes。然后使用 io_service 的 post 方法将事件发布到线程池。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-09-16
      • 1970-01-01
      • 2011-05-04
      • 1970-01-01
      • 1970-01-01
      • 2012-07-21
      • 1970-01-01
      相关资源
      最近更新 更多