Try to steal a task from another thread's queue
| 147 | |
| 148 | // Try to steal a task from another thread's queue |
| 149 | static task_run_handle steal_task(threadpool_data* impl, std::size_t thread_id) |
| 150 | { |
| 151 | // Make a list of victim thread ids and shuffle it |
| 152 | std::vector<std::size_t> victims(impl->thread_data.size()); |
| 153 | std::iota(victims.begin(), victims.end(), 0); |
| 154 | std::shuffle(victims.begin(), victims.end(), impl->thread_data[thread_id].rng); |
| 155 | |
| 156 | // Try to steal from another thread |
| 157 | for (std::size_t i: victims) { |
| 158 | // Don't try to steal from ourself |
| 159 | if (i == thread_id) |
| 160 | continue; |
| 161 | |
| 162 | if (task_run_handle t = impl->thread_data[i].queue.steal()) |
| 163 | return t; |
| 164 | } |
| 165 | |
| 166 | // No tasks found, but we might have missed one if it was just added. In |
| 167 | // practice this doesn't really matter since it will be handled by another |
| 168 | // thread. |
| 169 | return task_run_handle(); |
| 170 | } |
| 171 | |
| 172 | // Main task stealing loop which is used by worker threads when they have |
| 173 | // nothing to do. |
no test coverage detected