The Master-Slave Design Pattern

Designing a program as a society of active objects can lead to chaos. To avoid this fate, most multithreaded applications instantiate some variant of the Master-Slave design pattern.

Problem

An identical computation must be performed many times, but with different inputs and context. The results of these computations may need to be accumulated. If possible, we would like to take advantage of multiple processors.

Solution

A master thread creates multiple slave threads. Each slave performs a variation of the computation, reports the result to the master, then terminates. The master accumulates the results.

Discussion

Assume threads are represented as instances of a Thread class. Then an active object is an instance of a class derived from or associated with the Thread class:

In the Master-Slave pattern active master object creates many active slave objects. Each slave object retains a pointer back to its master:

Each slave performs some task, then reports its result back to the master. The master accumulates results and produces a final result.