-
Notifications
You must be signed in to change notification settings - Fork 287
Closed
Description
Currently, threading worker function wake-up mechanism is kind of a polling way which use sleep_or_yield() to yield CPU.
void worker() {
while (running) {
std::function<void()> task;
if (!paused && pop_task(task)) {
task();
tasks_total--;
} else {
sleep_or_yield();
}
}
}
How about to use std::condition_variable wait-notification wake-up mechanism? Thanks.
Something like below:
worker function changed to wait for notification
void worker() {
while (running) {
std::unique_lock lock(queue_mutex);
tasks_cv.wait(lock, [this] {
return !this->is_tasks_queue_empty() || !this->running();
});
std::function<void()> task;
if (!paused_ && pop_task(task)) {
task();
tasks_total--;
}
}
}
wait up worker by cv notification when task coming or thread pool reset or thread pool shutdown
template <typename F>
void push_task(const F &task) {
tasks_total++;
{
const std::scoped_lock lock(queue_mutex);
tasks.push(std::function<void()>(task));
}
tasks_cv.notify_all();
}
void reset(const ui32 &_thread_count = std::thread::hardware_concurrency()) {
bool was_paused = paused;
paused = true;
wait_for_tasks();
running = false;
tasks_cv.notify_all();
destroy_threads();
thread_count =
_thread_count ? _thread_count : std::thread::hardware_concurrency();
threads.reset(new std::thread[thread_count]);
paused = was_paused;
create_threads();
running = true;
}
~thread_pool() {
wait_for_tasks();
running = false;
tasks_cv.notify_all();
destroy_threads();
}
Metadata
Metadata
Assignees
Labels
No labels