aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorJohannes Stölp <johannes.stoelp@gmail.com>2020-10-22 20:24:56 +0200
committerGitHub <noreply@github.com>2020-10-22 20:24:56 +0200
commit38b8a8b97e0483cb9da5b2018f8d155be09761b9 (patch)
treeeea70053287689f266428fc9ed2c2e425079078b
parent3b4a6097dee760d22eecd97ebe041c69da6b056a (diff)
downloadmatcha-threads-38b8a8b97e0483cb9da5b2018f8d155be09761b9.tar.gz
matcha-threads-38b8a8b97e0483cb9da5b2018f8d155be09761b9.zip
fix memory leak when destroying Thread objects (#3)
-rw-r--r--lib/executor.cc2
-rw-r--r--lib/thread.cc16
-rw-r--r--lib/thread.h10
3 files changed, 20 insertions, 8 deletions
diff --git a/lib/executor.cc b/lib/executor.cc
index bfc268a..52bdf01 100644
--- a/lib/executor.cc
+++ b/lib/executor.cc
@@ -27,6 +27,6 @@ namespace nMatcha {
}
void Executor::yield_to(const Thread* t) {
- ::yield(t->mStackPtr, &mStackPtr);
+ ::yield(t->mStack.mPtr, &mStackPtr);
}
} // namespace nMatcha
diff --git a/lib/thread.cc b/lib/thread.cc
index 424041d..304091d 100644
--- a/lib/thread.cc
+++ b/lib/thread.cc
@@ -18,7 +18,7 @@ namespace {
} // namespace
namespace nMatcha {
- Thread::Thread() : mStackPtr(nullptr), mFinished(false), mExecutor(nullptr) {
+ Thread::Thread() : mStack{}, mFinished(false), mExecutor(nullptr) {
const long PAGE_SIZE = get_pagesize();
const long STACK_SIZE = 8 * PAGE_SIZE;
@@ -35,10 +35,18 @@ namespace nMatcha {
assert(ret == 0);
// Adjust stack pointer, as stack grows downwards.
- mStackPtr = static_cast<uint8_t*>(stack) + STACK_SIZE;
+ mStack.mPtr = static_cast<uint8_t*>(stack) + STACK_SIZE;
+ mStack.mBottom = stack;
+ mStack.mSize= STACK_SIZE;
+
// Arch specific stack initialization.
- mStackPtr = init_stack(mStackPtr, Thread::entry, static_cast<void*>(this));
+ mStack.mPtr = init_stack(mStack.mPtr, Thread::entry, static_cast<void*>(this));
+ }
+
+ Thread::~Thread() {
+ int ret = ::munmap(mStack.mBottom, mStack.mSize);
+ assert(ret == 0);
}
bool Thread::isFinished() const {
@@ -60,7 +68,7 @@ namespace nMatcha {
void Thread::yield() {
assert(mExecutor);
- ::yield(mExecutor->getStackPtr(), &mStackPtr);
+ ::yield(mExecutor->getStackPtr(), &mStack.mPtr);
}
std::unique_ptr<Thread> FnThread::make(UserFn f) {
diff --git a/lib/thread.h b/lib/thread.h
index 3dfa457..4cae2e1 100644
--- a/lib/thread.h
+++ b/lib/thread.h
@@ -33,7 +33,7 @@ namespace nMatcha {
Thread(const Thread&) = delete;
Thread& operator=(const Thread&) = delete;
Thread();
- virtual ~Thread() {}
+ virtual ~Thread();
bool isFinished() const;
@@ -42,9 +42,13 @@ namespace nMatcha {
private:
virtual void threadFn() = 0;
-
static void entry(void* ctx);
- void* mStackPtr;
+
+ struct Stack {
+ void* mBottom;
+ size_t mSize;
+ void* mPtr;
+ } mStack;
bool mFinished;
friend struct Executor;