Thread Local Summation: Using Local Variable
Let’s combine the two previous strategies for adding the numbers. I will use four threads and minimize the synchronization between the threads.
Using a Local Variable
Since each thread can use a local summation variable, it can do its job without synchronization; synchronization is only necessary to sum up the local variables. The summation of the local variables is a critical section that must be protected. This can be done in various ways. A quick remark: since only four additions take place, it doesn’t matter from a performance perspective which synchronization I use. Anyway, I will use an
std::lock_guard - an atomic with sequential consistency and relaxed semantic - for the summation.