diff options
author | johannst <johannes.stoelp@gmail.com> | 2020-09-18 01:36:00 +0200 |
---|---|---|
committer | johannst <johannes.stoelp@gmail.com> | 2020-09-18 01:36:00 +0200 |
commit | d89c25701381b393839ff38f93f198c4105b2c21 (patch) | |
tree | 96b5a81b411ac1b158d9e9df6dac09063cd53fc1 | |
parent | ec45be0578fb50ad4f3df28275f01d82a6d7b518 (diff) | |
download | matcha-threads-d89c25701381b393839ff38f93f198c4105b2c21.tar.gz matcha-threads-d89c25701381b393839ff38f93f198c4105b2c21.zip |
move yielding into Thread base class + make user fn a pure virtual fn and require user to derive from Thread
-rw-r--r-- | example/test.cc | 28 | ||||
-rw-r--r-- | lib/matcha.cc | 12 | ||||
-rw-r--r-- | lib/matcha.h | 18 |
3 files changed, 25 insertions, 33 deletions
diff --git a/example/test.cc b/example/test.cc index 7307bec..b436708 100644 --- a/example/test.cc +++ b/example/test.cc @@ -3,30 +3,18 @@ #include <cassert> #include <cstdio> -Thread* gThread1 = nullptr; - -void thread1_1() { - puts("thread1_1"); -} - -void thread1() { - puts("start thread1"); - thread1_1(); - puts("finish thread1"); - - assert(gThread1 != nullptr); - yield_from(*gThread1); -} +struct Thread1 : public Thread { + virtual void threadFn() override { + puts("start threadFn -> yield()"); + yield(); + puts("return from yield() -> finish threadFn"); + } +} gThread1; int main() { puts("start main thread"); - Thread t(thread1); - gThread1 = &t; - - yield_to(t); - - gThread1 = nullptr; + gThread1.yield_to(); puts("finish main thread"); return 0; diff --git a/lib/matcha.cc b/lib/matcha.cc index 3f7cd7b..561a08f 100644 --- a/lib/matcha.cc +++ b/lib/matcha.cc @@ -14,7 +14,7 @@ long get_pagesize() { return sysconf(_SC_PAGESIZE); } -Thread::Thread(void (*fn)()) : mUserFn(fn) { +Thread::Thread() { const long PAGE_SIZE = get_pagesize(); const long STACK_SIZE = 8 * PAGE_SIZE; @@ -53,16 +53,16 @@ void Thread::entry(void* obj) { Thread* t = static_cast<Thread*>(obj); puts("thread entry"); - t->mUserFn(); + t->threadFn(); puts("thread done"); } void* gOriginalStack; -void yield_to(const Thread& t) { - yield(t.mStackPtr, &gOriginalStack); +void Thread::yield() { + ::yield(gOriginalStack, &mStackPtr); } -void yield_from(Thread& t) { - yield(gOriginalStack, &t.mStackPtr); +void Thread::yield_to() const { + ::yield(mStackPtr, &gOriginalStack); } diff --git a/lib/matcha.h b/lib/matcha.h index 905107f..1506081 100644 --- a/lib/matcha.h +++ b/lib/matcha.h @@ -1,14 +1,18 @@ struct Thread { Thread(const Thread&) = delete; Thread& operator=(const Thread&) = delete; - Thread(void (*fn)()); + Thread(); - static void entry(void* obj); + virtual void threadFn() = 0; + + // use from executor + void yield_to() const; + + protected: + // use in thread + void yield(); - // private: + private: + static void entry(void* obj); void* mStackPtr; - void (*mUserFn)(); }; - -void yield_to(const Thread& t); -void yield_from(Thread& t); |