-
-
Notifications
You must be signed in to change notification settings - Fork 40
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[FEATURE] Add Way to Initialize Threads Before Workers Receive Work #58
Comments
Hi there 👋 Interesting suggestion! Would you mind sharing some example code (or pseudo code) of how you would imagine this working or what the API would look like? |
Here's an idea: class thread_pool {
public:
explicit thread_pool(
const FunctionType& init_function,
const unsigned int &number_of_threads = std::thread::hardware_concurrency())
: tasks_(number_of_threads) {
std::size_t current_id = 0;
for (std::size_t i = 0; i < number_of_threads; ++i) {
priority_queue_.push_back(size_t(current_id));
threads_.emplace_back([&, id = current_id, init = init_function](const std::stop_token &stop_tok) {
std::invoke(init);
// other stuff
});
}
}
}; |
To be fair, a simple lambda ( See usage from BS thread pool: Or DPDK: The DPDK case is interesting because they also allow storing a deinit callback to be executed when the worker thread (lcore in their nomenclature) is removed from the pool (in case of dynamic resizing, or the pool is destroyed). Use cases for deinit are much less frequent than init though, and trickier to get right (e.g. you need to ensure the deinit is called if an exception is thrown, so there ideally has to be some form of scoped guard), so I think it can be skipped. I would imagine the API could look like (pseudo code):
|
Awesome thanks! |
Actually, this will not fully address #36 since setting the stack size of the thread has to be done before the thread is created, which makes sense. I still think the init function is a good idea and will still add it. |
That looks perfect :-) thanks a lot ! |
It would be good to be able to run an init function on all threads of the pool to be executed prior to any other task.
In my use case, that would be to pin each worker affinity and set a thread name, but other use cases could be setting a specific stack size, etc.
The text was updated successfully, but these errors were encountered: