April 2020
Intermediate to advanced
412 pages
9h 58m
English
We are creating an application that updates all elements of an array using multiple worker threads. For expensive update operations, this approach can result in substantial performance gains on a multi-core platform.
The difficulty is sharing the work between multiple worker threads, given that each of them may require a different amount of time to process a data element.
We use a shared_index atomic variable to store an index of the next element that has not yet been claimed by any of the worker threads. This variable, along with the array to be processed, is declared as a global variable:
std::atomic<size_t> shared_index{0};std::vector<int> data;
Our worker function resembles the worker function from earlier recipes but ...