This page goes over the absolute basics of Boost threads [1].
It goes over topics like creating a thread and joining it.
Readers familiar with threads might find this page too simplistic.
Therefore, they should start with the producer-consumer page because the complete example might be a better starting point for them.
The page will start with simple examples showing how threads are created and joined and will look at the way thread scheduling affects the order of execution.
A custom class containing all the example functions will be used.
This usage of a class is done because the creation of threads works differently for static and non-static thread functions.
When the function the thread should run is not part of any class, the same code as the example for static functions can be used.
The class is defined as follows in the header file:
When a thread is created, it will have the type boost::thread.
A thread can be created using boost::thread(functionName), creating a thread that executes the functionName.
This thread can be saved inside of a variable with the type boost::thread.
The thread can be saved using the assignment operator or a shorthand notation.
The external scheduler used by threads will handle calling the thread.
The only action the programmer needs to take is to join the thread.
Joining a thread will pause the current function until the thread has finished running.
The following code example creates a thread and joins it to ensure it finishes running.
Please note that threads do not work deterministically, so the provided output can differ based on the order in which the threads are executed.
When using non-static functions in a class, the class instance of the function also needs to be provided.
This instance can be provided using the second parameter of the thread constructor.
If the function creating the thread belongs to the same class instance as the thread, then the ‘this’ keyword can reference the class instance.
Any parameters the function the thread will run should require can be added after the function name and optional instance parameters.