summaryrefslogtreecommitdiffstats
path: root/lib/base/threadpool.hpp
blob: d30fa694c9aef23cc06dfeff34ef8618639767bc (plain)
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
/* Icinga 2 | (c) 2012 Icinga GmbH | GPLv2+ */

#ifndef THREADPOOL_H
#define THREADPOOL_H

#include "base/atomic.hpp"
#include "base/configuration.hpp"
#include "base/exception.hpp"
#include "base/logger.hpp"
#include <cstddef>
#include <exception>
#include <functional>
#include <memory>
#include <thread>
#include <boost/asio/post.hpp>
#include <boost/asio/thread_pool.hpp>
#include <boost/thread/locks.hpp>
#include <boost/thread/shared_mutex.hpp>
#include <cstdint>

namespace icinga
{

enum SchedulerPolicy
{
	DefaultScheduler,
	LowLatencyScheduler
};

/**
 * A thread pool.
 *
 * @ingroup base
 */
class ThreadPool
{
public:
	typedef std::function<void ()> WorkFunction;

	ThreadPool();
	~ThreadPool();

	void Start();
	void Stop();
	void Restart();

	/**
	 * 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) {
			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;
		}
	}

	/**
	 * 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;
	Atomic<uint_fast64_t> m_Pending;

	void InitializePool();
};

}

#endif /* THREADPOOL_H */