Approach 1: Use a Synchronized Write Position

Learn how to use a synchronized write position approach with atomic size_t and fetch_add() to avoid multiple threads writing to the same index in parallel algorithms.

We'll cover the following

Overview

The first approach we might consider is to synchronize the write position by using an atomic size_t and the fetch_add() member function. Whenever a thread tries to write a new element, it fetches the current index and adds one atomically; thus, each value is written to a unique index.

In our code, we will split the algorithm into two functions: an inner function and an outer function. The atomic write index will be defined in the outer function, whereas the main part of the algorithm will be implemented in the inner function.

Inner function

The inner function requires an atomic size_t that synchronizes the write positions. As the algorithm is recursive, it cannot store the atomic size_t itself; it requires an outer function to invoke the algorithm:

Get hands-on with 1200+ tech skills courses.