DPsim
Loading...
Searching...
No Matches
Scheduler.h
Go to the documentation of this file.
1/* Copyright 2017-2021 Institute for Automation of Complex Power Systems,
2 * EONERC, RWTH Aachen University
3 *
4 * This Source Code Form is subject to the terms of the Mozilla Public
5 * License, v. 2.0. If a copy of the MPL was not distributed with this
6 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
7 *********************************************************************************/
8
9#pragma once
10
11#include <dpsim-models/Task.h>
12
13#include <dpsim-models/Logger.h>
14#include <dpsim/Definitions.h>
15
16#include <atomic>
17#include <chrono>
18#include <condition_variable>
19#include <deque>
20#include <mutex>
21#include <thread>
22#include <unordered_map>
23
24namespace DPsim {
25// TODO extend / subclass
27
28class Scheduler {
29public:
32 typedef std::unordered_map<CPS::Task::Ptr, std::deque<CPS::Task::Ptr>> Edges;
34 typedef std::chrono::steady_clock::duration TaskTime;
35
37 Scheduler(CPS::Logger::Level logLevel = CPS::Logger::Level::off)
38 : mRoot(std::make_shared<Root>()),
39 // Logging
40 mLogLevel(logLevel), mSLog(CPS::Logger::get("scheduler", logLevel)) {
41 mSLog->set_pattern("[%L] %v");
42 }
43
44 virtual ~Scheduler() {}
45
46 // #### Interface functions ####
47
49 virtual void createSchedule(const CPS::Task::List &tasks,
50 const Edges &inEdges, const Edges &outEdges) = 0;
52 virtual void step(Real time, Int timeStepCount) = 0;
56 virtual Bool runSimulation(Real, Int, UInt) { return false; }
58 virtual void stop() {}
59
62 void resolveDeps(CPS::Task::List &tasks, Edges &inEdges, Edges &outEdges);
63
64 // Special attribute that can be returned in the modified attributes of a task
65 // to mark that this task has external side-effects (like logging / interfacing)
66 // and thus has to be executed even though it doesn't modify any attribute.
67 // TODO is it really fine to use nullptr or should we create a special sentinel attribute?
69
73
76 class Root : public CPS::Task {
77 public:
78 Root() : Task("Root") { mAttributeDependencies.push_back(external); }
79
80 void execute(Real time, Int timeStepCount) { throw SchedulingException(); }
81 };
82
83protected:
85 void topologicalSort(const CPS::Task::List &tasks, const Edges &inEdges,
86 const Edges &outEdges, CPS::Task::List &sortedTasks);
89 static void levelSchedule(const CPS::Task::List &tasks, const Edges &inEdges,
90 const Edges &outEdges,
91 std::vector<CPS::Task::List> &levels);
92
93 void initMeasurements(const CPS::Task::List &tasks);
96 void updateMeasurement(CPS::Task *task, TaskTime time);
98 void writeMeasurements(CPS::String filename);
100 void readMeasurements(
101 CPS::String filename,
102 std::unordered_map<CPS::String, TaskTime::rep> &measurements);
105
112
113private:
114 // Accumulate compact per-task statistics instead of retaining every sample.
115 struct TaskMeasurement {
116 TaskTime total{};
117 TaskTime minimum{};
118 TaskTime maximum{};
119 std::size_t count = 0;
120 };
121 std::unordered_map<CPS::Task *, TaskMeasurement> mMeasurements;
122};
123
127class Barrier {
128public:
130 Barrier() = delete;
133 Barrier(Int limit, Bool useCondition = false)
134 : mLimit(limit), mCount(0), mGeneration(0), mUseCondition(useCondition) {}
135
139 void wait() {
140 if (mUseCondition) {
141 std::unique_lock<std::mutex> lk(mMutex);
142 Int gen = mGeneration;
143 mCount++;
144 if (mCount == mLimit) {
145 mCount = 0;
146 mGeneration++;
147 lk.unlock();
148 mCondition.notify_all();
149 } else {
150 // necessary because of spurious wakeups
151 while (gen == mGeneration)
152 mCondition.wait(lk);
153 }
154 } else {
155 Int gen = mGeneration.load(std::memory_order_acquire);
156 // We need at least one release from each thread to ensure that
157 // every write from before the wait() is visible in every other thread,
158 // and the fetch needs to be an acquire anyway, so use acq_rel instead of acquire.
159 // (This generates the same code on x86.)
160 if (mCount.fetch_add(1, std::memory_order_acq_rel) == mLimit - 1) {
161 mCount.store(0, std::memory_order_relaxed);
162 mGeneration.fetch_add(1, std::memory_order_release);
163 } else {
164 while (mGeneration.load(std::memory_order_acquire) == gen)
165 ;
166 }
167 }
168 }
169
174 void signal() {
175 if (mUseCondition) {
176 std::unique_lock<std::mutex> lk(mMutex);
177 mCount++;
178 if (mCount == mLimit) {
179 mCount = 0;
180 mGeneration++;
181 lk.unlock();
182 mCondition.notify_all();
183 }
184 } else {
185 // No release here, as this call does not provide any synchronization anyway.
186 if (mCount.fetch_add(1, std::memory_order_acquire) == mLimit - 1) {
187 mCount.store(0, std::memory_order_relaxed);
188 mGeneration.fetch_add(1, std::memory_order_release);
189 }
190 }
191 }
192
193private:
195 Int mLimit;
197 std::atomic<Int> mCount;
199 std::atomic<Int> mGeneration;
200 Bool mUseCondition;
201
202 std::mutex mMutex;
203 std::condition_variable mCondition;
204};
205
206class BarrierTask : public CPS::Task {
207public:
208 typedef std::shared_ptr<BarrierTask> Ptr;
209 void addBarrier(Barrier *b);
210 void execute(Real time, Int timeStepCount);
211
212private:
213 std::vector<Barrier *> mBarriers;
214};
215
216class Counter {
217public:
218 Counter() : mValue(0) {}
219
220 void inc() { mValue.fetch_add(1, std::memory_order_release); }
221
222 void wait(Int value) {
223 for (Int spin = 0; mValue.load(std::memory_order_acquire) != value;
224 ++spin) {
225 if ((spin & 63) == 63)
226 std::this_thread::yield();
227 }
228 }
229
230private:
231 std::atomic<Int> mValue;
232};
233} // namespace DPsim
AttributePointer< AttributeBase > Ptr
Definition Attribute.h:122
spdlog::level::level_enum Level
Definition Logger.h:33
std::shared_ptr< spdlog::logger > Log
Definition Logger.h:34
Tasks to be defined by every component.
Definition Task.h:25
std::vector< AttributeBase::Ptr > mAttributeDependencies
Definition Task.h:69
Task()
Definition Task.h:30
std::shared_ptr< Task > Ptr
Definition Task.h:27
std::vector< Ptr > List
Definition Task.h:28
Barrier()=delete
Constructor without parameters is forbidden.
Barrier(Int limit, Bool useCondition=false)
Definition Scheduler.h:133
std::shared_ptr< BarrierTask > Ptr
Definition Scheduler.h:208
void addBarrier(Barrier *b)
void execute(Real time, Int timeStepCount)
void wait(Int value)
Definition Scheduler.h:222
void execute(Real time, Int timeStepCount)
Definition Scheduler.h:80
void resolveDeps(CPS::Task::List &tasks, Edges &inEdges, Edges &outEdges)
Definition Scheduler.cpp:92
void writeMeasurements(CPS::String filename)
Write measurement data to file.
Definition Scheduler.cpp:44
virtual Bool runSimulation(Real, Int, UInt)
Definition Scheduler.h:56
Scheduler(CPS::Logger::Level logLevel=CPS::Logger::Level::off)
Definition Scheduler.h:37
void topologicalSort(const CPS::Task::List &tasks, const Edges &inEdges, const Edges &outEdges, CPS::Task::List &sortedTasks)
Simple topological sort, filtering out tasks that do not need to be executed.
static void levelSchedule(const CPS::Task::List &tasks, const Edges &inEdges, const Edges &outEdges, std::vector< CPS::Task::List > &levels)
CPS::Logger::Level mLogLevel
Log level.
Definition Scheduler.h:109
void readMeasurements(CPS::String filename, std::unordered_map< CPS::String, TaskTime::rep > &measurements)
Read measurement data from file to use it for the scheduling.
Definition Scheduler.cpp:63
static CPS::AttributeBase::Ptr external
Definition Scheduler.h:68
CPS::Task::Ptr mRoot
Definition Scheduler.h:107
virtual ~Scheduler()
Definition Scheduler.h:44
TaskTime getAveragedMeasurement(CPS::Task::Ptr task)
Definition Scheduler.h:70
void initMeasurements(const CPS::Task::List &tasks)
Definition Scheduler.cpp:24
virtual void step(Real time, Int timeStepCount)=0
Performs a single simulation step.
std::unordered_map< CPS::Task::Ptr, std::deque< CPS::Task::Ptr > > Edges
Definition Scheduler.h:32
virtual void createSchedule(const CPS::Task::List &tasks, const Edges &inEdges, const Edges &outEdges)=0
Creates the schedule for the given dependency graph.
void updateMeasurement(CPS::Task *task, TaskTime time)
Definition Scheduler.cpp:31
virtual void stop()
Called on simulation stop to reliably clean up e.g. running helper threads.
Definition Scheduler.h:58
std::chrono::steady_clock::duration TaskTime
Time measurement for the task execution.
Definition Scheduler.h:34
CPS::Logger::Log mSLog
Logger.
Definition Scheduler.h:111
std::string String
Definition Definitions.h:63
CPS::Logger Logger
Definition DPsim.h:40
CPS::Real Real
Definition Definitions.h:18
CPS::Int Int
Definition Definitions.h:22
CPS::Bool Bool
Definition Definitions.h:21
CPS::UInt UInt
Definition Definitions.h:23