Skip to content

Commit

Permalink
feat: add clear_tasks()
Browse files Browse the repository at this point in the history
  • Loading branch information
samangh committed Aug 6, 2024
1 parent 8bd7661 commit a32df2b
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
19 changes: 19 additions & 0 deletions include/thread_pool/thread_pool.h
Original file line number Diff line number Diff line change
Expand Up @@ -241,6 +241,25 @@ namespace dp {
}
}

/**
* @brief Makes best-case attempt to clear all tasks from the thread_pool
*/
void clear_tasks() {
// Note that this does not guarantee that all tasks will be cleared, as currently
// running tasks could add additional tasks. Also a thread could steal a task from
// another in the middle of this

size_t removed_task_count = 0;
for (auto &task_list : tasks_)
removed_task_count += task_list.tasks.clear();
in_flight_tasks_.fetch_sub(removed_task_count, std::memory_order_release);
unassigned_tasks_.fetch_sub(removed_task_count, std::memory_order_release);

// We signal at the end (instead of in previous for loop), to reduce the chance of a
// thread stealing a task from another.
for (auto &task_list : tasks_) task_list.signal.release();
}

private:
template <typename Function>
void enqueue_task(Function &&f) {
Expand Down
8 changes: 8 additions & 0 deletions include/thread_pool/thread_safe_queue.h
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,14 @@ namespace dp {
return data_.empty();
}

size_type clear() {
std::scoped_lock lock(mutex_);
auto size = data_.size();
data_.clear();

return size;
}

[[nodiscard]] std::optional<T> pop_front() {
std::scoped_lock lock(mutex_);
if (data_.empty()) return std::nullopt;
Expand Down

0 comments on commit a32df2b

Please sign in to comment.