From 27ec583dfadde68b3a72e6bea4ff7d33ddac4c77 Mon Sep 17 00:00:00 2001
From: Florian Schmaus <flow@cs.fau.de>
Date: Tue, 17 Jul 2018 12:07:45 +0200
Subject: [PATCH] Add Rutime::inRuntime() and Runtime::executeAndWait()

---
 emper/Dispatcher.hpp |  5 +++++
 emper/Runtime.cpp    | 22 ++++++++++++++++++++++
 emper/Runtime.hpp    |  4 ++++
 3 files changed, 31 insertions(+)

diff --git a/emper/Dispatcher.hpp b/emper/Dispatcher.hpp
index f40c747d..077cb5d6 100644
--- a/emper/Dispatcher.hpp
+++ b/emper/Dispatcher.hpp
@@ -56,5 +56,10 @@ public:
 		return currentFiber;
 	}
 
+	static bool isDispatchedControlFlow() {
+		const Fiber* fiber = getCurrentFiberPtr();
+		return fiber != nullptr;
+	}
+
 	friend ContextManager;
 };
diff --git a/emper/Runtime.cpp b/emper/Runtime.cpp
index 704d438c..ad848ce5 100644
--- a/emper/Runtime.cpp
+++ b/emper/Runtime.cpp
@@ -135,3 +135,25 @@ void Runtime::printLastRuntimeStats() {
 	currentRuntime->printStats();
 }
 
+bool Runtime::inRuntime() {
+	return dispatcher.isDispatchedControlFlow();
+}
+
+void Runtime::executeAndWait(std::function<void()> f) {
+	if (inRuntime()) {
+		ABORT("Ca not use executeAndWait() from within the Runtime");
+	}
+
+	std::mutex fiberFinished;
+	fiberFinished.lock();
+
+	Fiber* fiber = Fiber::from([&] {
+			f();
+
+			fiberFinished.unlock();
+		});
+
+	schedule(*fiber);
+
+	fiberFinished.lock();
+}
diff --git a/emper/Runtime.hpp b/emper/Runtime.hpp
index 5b443b3e..414befab 100644
--- a/emper/Runtime.hpp
+++ b/emper/Runtime.hpp
@@ -113,6 +113,10 @@ public:
 
 	void printStats();
 
+	bool inRuntime();
+
+	void executeAndWait(std::function<void()> f);
+
 	friend ContextManager;
 	friend Scheduler;
 	friend Dispatcher;
-- 
GitLab