1 /* Icinga 2 | (c) 2012 Icinga GmbH | GPLv2+ */
6 #include "base/i2-base.hpp"
7 #include "base/timer.hpp"
8 #include "base/ringbuffer.hpp"
9 #include <boost/thread/thread.hpp>
10 #include <boost/thread/mutex.hpp>
11 #include <boost/thread/condition_variable.hpp>
12 #include <boost/exception_ptr.hpp>
20 enum WorkQueuePriority
28 using TaskFunction = std::function<void ()>;
34 Task(TaskFunction function, WorkQueuePriority priority, int id)
35 : Function(std::move(function)), Priority(priority), ID(id)
38 TaskFunction Function;
39 WorkQueuePriority Priority{PriorityNormal};
43 bool operator<(const Task& a, const Task& b);
53 typedef std::function<void (boost::exception_ptr)> ExceptionCallback;
55 WorkQueue(size_t maxItems = 0, int threadCount = 1);
58 void SetName(const String& name);
59 String GetName() const;
61 boost::mutex::scoped_lock AcquireLock();
62 void EnqueueUnlocked(boost::mutex::scoped_lock& lock, TaskFunction&& function, WorkQueuePriority priority = PriorityNormal);
63 void Enqueue(TaskFunction&& function, WorkQueuePriority priority = PriorityNormal,
64 bool allowInterleaved = false);
65 void Join(bool stop = false);
67 template<typename VectorType, typename FuncType>
68 void ParallelFor(const VectorType& items, const FuncType& func)
70 using SizeType = decltype(items.size());
72 SizeType totalCount = items.size();
74 auto lock = AcquireLock();
78 for (int i = 0; i < m_ThreadCount; i++) {
79 SizeType count = totalCount / static_cast<SizeType>(m_ThreadCount);
80 if (static_cast<SizeType>(i) < totalCount % static_cast<SizeType>(m_ThreadCount))
83 EnqueueUnlocked(lock, [&items, func, offset, count, this]() {
84 for (SizeType j = offset; j < offset + count; j++) {
85 RunTaskFunction([&func, &items, j]() {
94 ASSERT(offset == items.size());
97 bool IsWorkerThread() const;
99 size_t GetLength() const;
100 size_t GetTaskCount(RingBuffer::SizeType span);
102 void SetExceptionCallback(const ExceptionCallback& callback);
104 bool HasExceptions() const;
105 std::vector<boost::exception_ptr> GetExceptions() const;
106 void ReportExceptions(const String& facility) const;
109 void IncreaseTaskCount();
114 static std::atomic<int> m_NextID;
116 bool m_Spawned{false};
118 mutable boost::mutex m_Mutex;
119 boost::condition_variable m_CVEmpty;
120 boost::condition_variable m_CVFull;
121 boost::condition_variable m_CVStarved;
122 boost::thread_group m_Threads;
124 bool m_Stopped{false};
126 std::priority_queue<Task, std::deque<Task> > m_Tasks;
128 ExceptionCallback m_ExceptionCallback;
129 std::vector<boost::exception_ptr> m_Exceptions;
130 Timer::Ptr m_StatusTimer;
131 double m_StatusTimerTimeout;
133 RingBuffer m_TaskStats;
134 size_t m_PendingTasks{0};
135 double m_PendingTasksTimestamp{0};
137 void WorkerThreadProc();
138 void StatusTimerHandler();
140 void RunTaskFunction(const TaskFunction& func);
145 #endif /* WORKQUEUE_H */