From 8387c629eaf3b90c9f57e2b333982ac9e6f6944a Mon Sep 17 00:00:00 2001 From: Vaclav Petras Date: Thu, 1 Oct 2026 11:34:31 -0400 Subject: [PATCH] r.sim: Distribute walkers to threads with a worksharing loop The walker loop computed each thread's range of walkers by hand from the thread number and count. A worksharing loop with static schedule does the same with one pragma, and ends with an implicit barrier, so code after the loop in the same parallel region sees all walkers processed without an explicit barrier. The loop variable is private in a worksharing loop, so it is no longer listed as firstprivate. The parallel region is kept, rather than merged with the loop into a parallel for, to keep the loop body at its indentation. Single-threaded results do not change: the depth and discharge maps computed from the nc_spm elevation, with and without infiltration and diffusion, are byte-identical to those before this change, and the run time is the same within noise at 1, 4 and 8 threads. Written with the help of Claude Code. --- raster/r.sim/simlib/hydro.c | 15 ++------------- 1 file changed, 2 insertions(+), 13 deletions(-) diff --git a/raster/r.sim/simlib/hydro.c b/raster/r.sim/simlib/hydro.c index 0c03eb2476d..2bcc53bcc88 100644 --- a/raster/r.sim/simlib/hydro.c +++ b/raster/r.sim/simlib/hydro.c @@ -150,21 +150,10 @@ void main_loop(const Setup *setup, const Geometry *geometry, nwalka = 0; sim->nstack = 0; -#pragma omp parallel firstprivate(l, lw, k) reduction(+ : nwalka) +#pragma omp parallel firstprivate(l, k) reduction(+ : nwalka) { -#if defined(_OPENMP) - int steps = (sim->nwalk + omp_get_num_threads() - 1) / - omp_get_num_threads(); - int tid = omp_get_thread_num(); - int min_loop = tid * steps; - int max_loop = ((tid + 1) * steps) > sim->nwalk - ? sim->nwalk - : (tid + 1) * steps; - - for (lw = min_loop; lw < max_loop; lw++) { -#else +#pragma omp for schedule(static) for (lw = 0; lw < sim->nwalk; lw++) { -#endif if (sim->w[lw].m > EPS) { /* check the walker weight */ ++(nwalka); l = (int)((sim->w[lw].x + stxm) / geometry->stepx) -