Parallel C++ from scratch
Splitting a loop across CPU threads with oneTBB, and why the way the work is divided matters as much as the number of threads.
Running a loop on eight threads does not make it eight times faster. It only gets close when every thread finishes at about the same moment, and that depends on how the loop’s iterations are divided up. This course starts there: the same tbb::parallel_for over 262,144 jobs, run with two different partitioners, first on jobs of equal length and then on jobs whose lengths vary.
The course is short so far. It covers workload distribution with oneTBB; OpenMP and MPI are planned in the repository but not written yet, and will appear here when they are.
Prerequisites
- C++17: lambdas,
std::vector,<random>. - A multi-core machine. The timings below come from a 22-thread CPU under WSL2, with each run pinned to a fixed number of CPUs.
Running the code
The programs need the oneTBB headers and library. On Ubuntu, sudo apt install libtbb-dev; without root, pip install tbb-devel provides both in a Python environment.
cd parallel_cpp_from_scratch/01_workload_distribution/1_uneven_job_length
g++ -std=c++17 -O3 0_static.cpp -o 0_static -ltbb
time ./0_static
time taskset -c 0-3 ./0_static # the same, limited to 4 CPUs
oneTBB starts one worker per CPU it is allowed to use, so taskset is a simple way to vary the thread count without changing the code.
What to watch for
The repository simulates work with std::this_thread::sleep_for. Sleeping is not computing, and on this machine every call oversleeps by about 80 µs, which hides most of the effect the course is about. Lesson 2 replaces it with a busy-wait and gets measurements that match a back-of-the-envelope prediction to within about 6%.