C++ Boost

Boost.Threads

thread_group


Introduction
Header
Synopsis
Members
Example

Introduction

The thread_group class provides a container for easy grouping of threads to simplify several common thread creation and management idioms.

All thread_group member functions are thread-safe, except destruction.

Header

#include <boost/thread/thread.hpp>

Synopsis

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

Members


Constructor

    thread_group();

Effects: Constructs an empty thread_group container.


Destructor

    ~thread_group();

Effects: Destroys each contained thread object. Destroys *this.

Notes: Behavior is undefined if another thread references *this during the execution of the destructor.


create_thread

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

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

Returns: Pointer to the newly created thread.


add_thread

    void add_thread(thread* thrd);

Effects: 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);

Effects: Removes *this's list of managed thread objects.

Throws: ? if thrd is not it *this's list of managed thread objects.


join_all

    void join_all();

Effects: Calls join() on each of the managed thread objects.


Example Usage

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

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

Revised 05 November, 2001

© Copyright William E. Kempf 2001 all rights reserved.