| 141 | #endif |
| 142 | |
| 143 | static void run_pthreads(int count, cbm_parallel_fn fn, void *ctx, int nworkers) { |
| 144 | _Atomic int next_idx = 0; |
| 145 | |
| 146 | pthread_worker_arg_t wa = { |
| 147 | .fn = fn, |
| 148 | .ctx = ctx, |
| 149 | .next_idx = &next_idx, |
| 150 | .count = count, |
| 151 | }; |
| 152 | |
| 153 | cbm_thread_t *threads = (cbm_thread_t *)malloc((size_t)nworkers * sizeof(cbm_thread_t)); |
| 154 | if (!threads) { |
| 155 | run_serial(count, fn, ctx); |
| 156 | return; |
| 157 | } |
| 158 | |
| 159 | for (int i = 0; i < nworkers; i++) { |
| 160 | if (cbm_thread_create(&threads[i], CBM_WORKER_STACK_SIZE, pthread_worker, &wa) != 0) { |
| 161 | /* Failed to create thread — let remaining work run in main thread */ |
| 162 | nworkers = i; |
| 163 | break; |
| 164 | } |
| 165 | } |
| 166 | |
| 167 | /* Main thread also participates */ |
| 168 | while (WP_TRUE) { |
| 169 | int idx = atomic_fetch_add_explicit(&next_idx, WP_STEP, memory_order_relaxed); |
| 170 | if (idx >= count) { |
| 171 | break; |
| 172 | } |
| 173 | fn(idx, ctx); |
| 174 | } |
| 175 | |
| 176 | for (int i = 0; i < nworkers; i++) { |
| 177 | cbm_thread_join(&threads[i]); |
| 178 | } |
| 179 | |
| 180 | free(threads); |
| 181 | } |
| 182 | |
| 183 | /* ── Public API ──────────────────────────────────────────────────── */ |
| 184 |
no test coverage detected