C++ Boost

Boost.Threads

thread_group


The thread_group class provides easy grouping of threads in order to simplify several common thread creation and management idioms.

Header

#include <boost/thread/thread.hpp>

Public Interface


    class thread_group : boost::noncopyable
    {
    public:
        thread_group();
        ~thread_group();

        thread* create_thread(const boost::function0<void>& threadfunc);
        void add_thread(thread* thrd);
        void remove_thread(thread* thrd);
        void join_all();
    };

Constructor

    thread_group();

Constructs a thread_group object.

Destructor

    ~thread_group();

Destructs a thread_group object, deleting the managed thread objects.

create_thread

    thread* create_thread(const boost::function0<void>& threadfunc);

Creates a new thread object that executes threadfunc and adds it to the thread_group object's list of managed thread objects.

add_thread

    void add_thread(thread* thrd);

Adds thrd to the thread_group object's list of managed thread objects. The thrd object must have been allocated via operator new and will be deleted when the group is destroyed.

remove_thread

    void remove_thread(thread* thrd);

Removes thrd from the thread_group object's list of managed thread objects.

join_all

    void join_all();

Calls join() for each of the managed thread objects.

Example Usage

#include <boost/thread/thread.hpp>
#include <iostram>

int count = 0;
boost::mutex mutex;

void increment_count()
{
   boost::mutex::lock lock(mutex);
   std::cout << "count = " << ++count << std::endl;
}

int main(int argc, char* argv[])
{
   boost::thread_group threads;
   for (int i = 0; i < 10; ++i)
      threads.create_thread(&increment_count);
   threads.join_all();
}

The output is:

count = 1
count = 2
count = 3
count = 4
count = 5
count = 6
count = 7
count = 8
count = 9
count = 10

Copyright William E. Kempf 2001 all rights reserved.