boost::thread和创建线程池!

4
boost::thread类有一个默认构造函数,它会给出一个“非线程”,那么这对于什么有好处呢?我可以在代码后面给它一个要执行的函数吗?
另外还有一个问题:
我正在尝试编写一个具有分阶段体系结构(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();
}

线程组的大小不断增长。那些已经完成的线程会发生什么?如何重复使用这些线程并保持线程组大小为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();
}

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

我非常感谢任何帮助。非常感谢。

1个回答

4

一种选项是使用boost asio。请查看线程池的示例:http://think-async.com/Asio/Recipes。然后,您可以使用io_service的post方法将事件发布到线程池。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接