4
votes

boost::thread class has a default constructor which gives a "Not-a-thread", so what is

boost::thread t1;

good for? Can I give it a function to execute later in the code?

and another question:

I'm trying to write a little server which has a staged architecture (SEDA), there are a number of worker threads in each stage and the stages are connected with event queues. when i create the pool with 4 worker threads using boost::thread_group like this: (I've removed the condition variable on the queue to clean up here, and also assuming the size of the queue is always 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();
}

the thread_group keeps growing in size. what happens to those threads in the group which have finished and How can i reuse those threads and keep the thread_group size at 4?

i saw this question and instead of the above code used this:

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

so what's the difference and which one has a better performance? Will there be a memory leak? or is there another way to create a simple pool of threads?

I'd appreciate any help. Thank you very much.

1

1 Answers

3
votes

One options is to use boost asio. Have a look at the recipe for a thread pool: http://think-async.com/Asio/Recipes. You then post events to the thread pool using the post method of the io_service.