icinga2/lib/base/threadpool.hpp

99 lines
1.9 KiB
C++
Raw Normal View History

/* Icinga 2 | (c) 2012 Icinga GmbH | GPLv2+ */
2012-06-24 02:56:48 +02:00
2013-03-25 18:36:15 +01:00
#ifndef THREADPOOL_H
#define THREADPOOL_H
2012-06-24 02:56:48 +02:00
2019-08-14 17:12:59 +02:00
#include "base/atomic.hpp"
#include "base/exception.hpp"
#include "base/logger.hpp"
#include <cstddef>
#include <exception>
#include <functional>
#include <memory>
2017-11-21 12:12:58 +01:00
#include <thread>
#include <boost/asio/post.hpp>
#include <boost/asio/thread_pool.hpp>
#include <boost/thread/locks.hpp>
#include <boost/thread/shared_mutex.hpp>
2019-08-14 17:12:59 +02:00
#include <cstdint>
2013-03-15 18:21:29 +01:00
2012-06-24 02:56:48 +02:00
namespace icinga
{
enum SchedulerPolicy
{
DefaultScheduler,
LowLatencyScheduler
};
2012-09-17 13:35:55 +02:00
/**
2013-03-25 18:36:15 +01:00
* A thread pool.
2012-09-17 13:35:55 +02:00
*
* @ingroup base
*/
2017-12-31 07:22:16 +01:00
class ThreadPool
2012-06-24 02:56:48 +02:00
{
public:
typedef std::function<void ()> WorkFunction;
2013-03-25 18:36:15 +01:00
ThreadPool(size_t threads = std::thread::hardware_concurrency() * 2u);
~ThreadPool();
2012-06-24 02:56:48 +02:00
void Start();
void Stop();
2013-02-18 14:40:24 +01:00
/**
* Appends a work item to the work queue. Work items will be processed in FIFO order.
*
* @param callback The callback function for the work item.
* @returns true if the item was queued, false otherwise.
*/
template<class T>
bool Post(T callback, SchedulerPolicy)
{
boost::shared_lock<decltype(m_Mutex)> lock (m_Mutex);
if (m_Pool) {
2019-08-14 17:12:59 +02:00
m_Pending.fetch_add(1);
boost::asio::post(*m_Pool, [this, callback]() {
m_Pending.fetch_sub(1);
try {
callback();
} catch (const std::exception& ex) {
Log(LogCritical, "ThreadPool")
<< "Exception thrown in event handler:\n"
<< DiagnosticInformation(ex);
} catch (...) {
Log(LogCritical, "ThreadPool", "Exception of unknown type thrown in event handler.");
}
});
return true;
} else {
return false;
}
}
2013-03-25 18:36:15 +01:00
2019-08-14 17:12:59 +02:00
/**
* Returns the amount of queued tasks not started yet.
*
* @returns amount of queued tasks.
*/
inline uint_fast64_t GetPending()
{
return m_Pending.load();
}
private:
boost::shared_mutex m_Mutex;
std::unique_ptr<boost::asio::thread_pool> m_Pool;
size_t m_Threads;
2019-08-14 17:12:59 +02:00
Atomic<uint_fast64_t> m_Pending;
2012-06-24 02:56:48 +02:00
};
}
2019-04-23 16:59:49 +02:00
#endif /* THREADPOOL_H */