| 83 | |
| 84 | #if defined(CBM_MEMWASTE) && CBM_MEMWASTE |
| 85 | static void run_pthreads_counted(int count, cbm_parallel_fn fn, void *ctx, int nworkers, |
| 86 | void *site) { |
| 87 | _Atomic int next_idx = 0; |
| 88 | pthread_worker_arg_t wa = {.fn = fn, .ctx = ctx, .next_idx = &next_idx, .count = count}; |
| 89 | cbm_thread_t *threads = cbm_alloc(CBM_MEM_CLASS_OTHER, (size_t)nworkers * sizeof(cbm_thread_t)); |
| 90 | wp_counted_arg_t *args = cbm_calloc(CBM_MEM_CLASS_OTHER, (size_t)nworkers * sizeof(*args)); |
| 91 | if (!threads || !args) { |
| 92 | cbm_free(CBM_MEM_CLASS_OTHER, threads); |
| 93 | cbm_free(CBM_MEM_CLASS_OTHER, args); |
| 94 | run_serial(count, fn, ctx); |
| 95 | return; |
| 96 | } |
| 97 | int started = 0; |
| 98 | for (int i = 0; i < nworkers; i++) { |
| 99 | args[i].wa = &wa; |
| 100 | if (cbm_thread_create(&threads[i], CBM_WORKER_STACK_SIZE, pthread_worker_counted, |
| 101 | &args[i]) != 0) { |
| 102 | break; |
| 103 | } |
| 104 | started++; |
| 105 | } |
| 106 | int main_done = 0; |
| 107 | uint64_t main_ops_before = cbm_memev_thread_ops(); |
| 108 | while (WP_TRUE) { |
| 109 | int idx = atomic_fetch_add_explicit(&next_idx, WP_STEP, memory_order_relaxed); |
| 110 | if (idx >= count) { |
| 111 | break; |
| 112 | } |
| 113 | fn(idx, ctx); |
| 114 | main_done++; |
| 115 | } |
| 116 | uint64_t main_ops = cbm_memev_thread_ops() - main_ops_before; |
| 117 | for (int i = 0; i < started; i++) { |
| 118 | cbm_thread_join(&threads[i]); |
| 119 | } |
| 120 | int max_done = main_done; |
| 121 | uint64_t max_ops = main_ops; |
| 122 | uint64_t sum_ops = main_ops; |
| 123 | for (int i = 0; i < started; i++) { |
| 124 | if (args[i].done > max_done) { |
| 125 | max_done = args[i].done; |
| 126 | } |
| 127 | if (args[i].ops > max_ops) { |
| 128 | max_ops = args[i].ops; |
| 129 | } |
| 130 | sum_ops += args[i].ops; |
| 131 | } |
| 132 | int participants = started + 1; |
| 133 | uint64_t balanced_max = (uint64_t)participants * (uint64_t)max_done; |
| 134 | uint64_t imbalance = balanced_max > (uint64_t)count ? balanced_max - (uint64_t)count : 0; |
| 135 | cbm_work_note(CBM_WORK_PARALLEL_FOR, site, (uint64_t)count, imbalance, (uint64_t)participants); |
| 136 | cbm_work_note(CBM_WORK_POOL_OPS, site, sum_ops, (uint64_t)participants * max_ops - sum_ops, |
| 137 | (uint64_t)participants); |
| 138 | cbm_free(CBM_MEM_CLASS_OTHER, threads); |
| 139 | cbm_free(CBM_MEM_CLASS_OTHER, args); |
| 140 | } |
| 141 | #endif |
| 142 |
no test coverage detected