| 266 | |
| 267 | template <typename Condition> |
| 268 | bool ThreadPoolBase::WaitOrRunTasks(std::condition_variable &cv, Condition &&condition) { |
| 269 | // This function waits cooperatively for a condition (e.g. job completion) to be met - while |
| 270 | // it's not met, the calling thread participates in executing the tasks from this thread pool. |
| 271 | |
| 272 | // This function should be used only from within this thread pool's threads. |
| 273 | assert(this_thread_pool() == this); |
| 274 | |
| 275 | while (!shutdown_pending_) { |
| 276 | std::unique_lock lock(mtx_); |
| 277 | bool ret; |
| 278 | while (!(ret = condition()) && tasks_.empty()) |
| 279 | cv.wait_for(lock, std::chrono::microseconds(100)); |
| 280 | |
| 281 | if (ret || condition()) // re-evaluate the condition after the timeout, just in case |
| 282 | return true; |
| 283 | |
| 284 | if (shutdown_pending_) |
| 285 | return condition(); |
| 286 | |
| 287 | // The condition was not met in 100µs, let's try to pick up some tasks |
| 288 | |
| 289 | bool acquired = sem_.try_acquire(); |
| 290 | if (!acquired) |
| 291 | continue; // no tasks? spin |
| 292 | |
| 293 | assert(!tasks_.empty() && "Semaphore acquired but no tasks present."); |
| 294 | PopUnlockAndRunTask(lock); |
| 295 | } |
| 296 | return condition(); |
| 297 | } |
| 298 | |
| 299 | } // namespace dali |
no test coverage detected