BDE 4.14.0 Production release
Loading...
Searching...
No Matches
bslmt_threadgroup

Detailed Description

Outline

Purpose

Provide a container for managing a group of threads.

Classes

See also
bslmt_threadutil, 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

This section illustrates intended use of this component.

Example 1: Basic 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) {
++*d_value_p;
}
}
};
Definition bslmt_lockguard.h:234
Definition bslmt_mutex.h:315

The second executes the main body of the test:

{
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());
Definition bslma_testallocator.h:384
bsls::Types::Int64 numBytesInUse() const
Definition bslma_testallocator.h:1111
bsls::Types::Int64 numAllocations() const
Definition bslma_testallocator.h:1081
Definition bslmt_threadgroup.h:156