Files
thehub/libs/utils/WorkerThreads.h
tomFlowee bb7275466b Stop using deprecated asio io_service
This ports the io-service to the source compatible io-context
class, with the most work going to the WorkerThreads which owns
that one.
2025-02-08 19:05:26 +01:00

77 lines
2.6 KiB
C++

/*
* This file is part of the Flowee project
* Copyright (C) 2018-2025 Tom Zander <tom@flowee.org>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef FLOWEE_WORKERTHREADS_H
#define FLOWEE_WORKERTHREADS_H
#include <boost/asio/io_context.hpp>
#include <boost/asio/executor_work_guard.hpp>
#include <boost/thread.hpp>
/**
* This is a class that spawns a series of threads where jobs can be run on.
* The WorkerThreads class starts a list of threads based on the amount of
* cores detected on the hardware, each thread will then be run to become an
* event-queue based on the boost asio primitives.
*
* Notice that the threads catch exceptions and continue the next event
* in the event-queue after logging a generic message.
*/
class WorkerThreads
{
public:
/**
* Create all threads and start them.
* @param threadCount the number of threads to start, or -1 to use the hardware concurrency amount.
*/
WorkerThreads(int threadCount = -1);
~WorkerThreads();
/// request a peaceful shutdown of the threads. (thread-safe)
void stopThreads();
/// blocking wait until all threads finished.
void joinAll();
/// Return a ref to the ioContext owned by this WorkerThreads.
boost::asio::io_context& ioContext() const;
/**
* Wrapper function that allows users to create a thread on our thread-group.
*/
template<typename F>
boost::thread* createNewThread(F threadfunc) {
return m_threads.create_thread(threadfunc);
}
protected:
/// only called from constructor. Useful in unit tests.
void startThreads(int threadCount = -1);
private:
std::shared_ptr<boost::asio::io_context> m_context;
// work around weird template shit from boost that makes it impossible to reuse
// the same stack defined item multiple times.
struct Work {
Work(const std::shared_ptr<boost::asio::io_context> &context);
boost::asio::executor_work_guard<boost::asio::io_context::executor_type> work;
};
std::unique_ptr<Work> m_work;
boost::thread_group m_threads;
};
#endif