summaryrefslogtreecommitdiff
path: root/libadhocutil/runtimeContext.cpp
blob: 9ac7cea1d6a00c5481a3b74621149744cd1397f0 (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
#include "runtimeContext.h"
#include <cerrno>
#include <cstring>
#include <sys.h>

namespace AdHoc::System {

	RuntimeContext::RuntimeContext(size_t stacksize) : stack(stacksize)
	{
		if (getcontext(&ctxCallback) == -1) {
			throw SystemException("getcontext(3) failed", strerror(errno), errno);
		}
		ctxCallback.uc_stack.ss_sp = &stack.front();
		ctxCallback.uc_stack.ss_size = stacksize;
		ctxCallback.uc_link = &ctxInitial;
		makecontext(&ctxCallback, reinterpret_cast<void (*)()>(&RuntimeContext::callbackWrapper), 1, this);
	}

	void
	RuntimeContext::swapContext()
	{
		swapped = !swapped;
		if (swapped) {
			swapcontext(&ctxInitial, &ctxCallback);
		}
		else {
			if (!completed) {
				swapcontext(&ctxCallback, &ctxInitial);
			}
		}
	}

	bool
	RuntimeContext::hasCompleted() const
	{
		return completed;
	}

	void
	RuntimeContext::callbackWrapper(RuntimeContext * rc)
	{
		rc->callback();
		rc->completed = true;
	}

}