Pool Hooks

Writing hooks

Hooks are written by creating a class or a struct which inherits from the class ThreadPool::Hooks. You can then override whichever hooks you need.

Tasks Hooks

virtual void ThreadPool::Hooks::pre_task_hook()

Hook called before picking a task.

This hook will be called by a worker before a task is executed. The worker will not have anything locked when calling the hook. The worker will call in a “working” state. That means that if the hook takes too long, the worker will hold on the task execution and not run it.

virtual void ThreadPool::Hooks::post_task_hook()

Hook called after a task is done.

This hook will be called by a worker after a task is done. The worker will not have anything locked when calling the hook. The worker will call in a “working” state. That means that if the hook takes too long, the worker will hold and not pick a task until the hook is completed.

Workers Hooks

virtual void ThreadPool::Hooks::on_worker_add()

Hook called when a worker is added for a single task.

This hook will be called by the main thread (the thread making the call to run). It is called only when the ThreadPool automatically scales to add one more worker. The initials workers created by the ThreadPool will not notify this hook.

virtual void ThreadPool::Hooks::on_worker_die()

Hook called when a worker dies.

This hook will be called by the thread the ThreadPool is detroyed with. All workers will notify this hook.

Registering hooks

Hooks can be used to be notified when actions happens in the pool. The hooks are registered in the pool using the function:

void ThreadPool::ThreadPool::register_hooks(std::shared_ptr<Hooks> hooks)

Register a ThreadPool::Hooks class.

Parameters
  • hooks: The class to be registered

Example

Here is a simple example to use hooks with the Pool.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
#include <memory>

#include "threadpool.hpp"

struct TestHooks : public ThreadPool::Hooks
{
  void pre_task_hook() final
  {
    std::cout << "pre_task_hook\n";
  }

  void post_task_hook() final
  {
    std::cout << "post_task_hook\n";
  }
};

int main(void)
{
  ThreadPool::ThreadPool pool(1);
  std::shared_ptr<TestHooks> hooks(new TestHooks());
  pool.register_hooks(hooks);

  auto res = pool.run([]() { return 0; });
  res.wait();
}