Thread Local Summation: Using Local Variable

This lesson explains the solution for calculating the sum of a vector problem using a local variable in C++.

Let’s combine the two previous strategies for adding the numbers. I will use four threads and minimize the synchronization between the threads.

There are different ways to minimize the synchronization: local variables, thread-local data, and tasks

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.

std::lock_guard

Get hands-on with 1000+ tech skills courses.