Quick Links:

bal | bbl | bdl | bsl

Namespaces

Component bslmt_threadgroup
[Package bslmt]

Provide a container for managing a group of threads. More...

Namespaces

namespace  bslmt

Detailed Description

Outline
Purpose:
Provide a container for managing a group of threads.
Classes:
bslmt::ThreadGroup A container that manages a group of threads.
See also:
Component bslmt_threadutil, Component bslmt_threadattributes
Description:
This component provides a simple mechanism for managing a group of threads. The group is represented by an instance of the bslmt::ThreadGroup class. To use this component, the client code calls addThread, providing a function to be executed. The specified function is executed in a new thread managed by the thread group (note that addThread is thread-safe). The joinAll call blocks until all threads in the group have finished executing.
Thread Safety:
This component is thread-safe and thread-enabled, meaning that multiple threads may safely use their own instances or a shared instance of a bslmt::ThreadGroup object.
Usage:
The following usage example illustrates how bslmt::ThreadGroup might be used in a typical test driver to simplify the execution of a common function in multiple threads. Suppose that we are interested in creating a stress-test for the bslmt::Mutex class. The test is controlled by two parameters: the number of executions (defined by subsequent calls to lock and unlock, and the amount of contention, defined by the number of threads accessing the mutex. The test can be expressed as two functions. The first is executed in each thread via a functor object:
  class MutexTestJob {
      int           d_numIterations;
      int          *d_value_p;
      bslmt::Mutex *d_mutex_p;

    public:
      MutexTestJob(int numIterations, int *value, bslmt::Mutex *mutex)
      : d_numIterations(numIterations)
      , d_value_p(value)
      , d_mutex_p(mutex)
      {}

      void operator()() {
          for (int i = 0; i < d_numIterations; ++i) {
              bslmt::LockGuard<bslmt::Mutex> guard(d_mutex_p);
              ++*d_value_p;
          }
      }
  };
The second executes the main body of the test:
  bslma::TestAllocator ta;
  {
      const int NUM_ITERATIONS = 10000;
      const int NUM_THREADS    = 8;

      bslmt::Mutex   mutex;                     // object under test
      int            value = 0;

      MutexTestJob testJob(NUM_ITERATIONS, &value, &mutex);

      bslmt::ThreadGroup threadGroup(&ta);
      for (int i = 0; i < NUM_THREADS; ++i) {
          assert(0 == threadGroup.addThread(testJob));
      }
      threadGroup.joinAll();
      assert(NUM_ITERATIONS * NUM_THREADS == value);
  }
  assert(0 <  ta.numAllocations());
  assert(0 == ta.numBytesInUse());