diff options
Diffstat (limited to 'lib/thread.h')
-rw-r--r-- | lib/thread.h | 49 |
1 files changed, 41 insertions, 8 deletions
diff --git a/lib/thread.h b/lib/thread.h index c181425..3dfa457 100644 --- a/lib/thread.h +++ b/lib/thread.h @@ -8,23 +8,42 @@ namespace nMatcha { struct Executor; + // An abstract base class for implementing cooperative user threads. + // + // # Usage + // + // To implement a cooperative user thread following interface invoked by + // the Executor must be implemented: + // virtual void threadFn() = 0; + // By calling `yield()` a thread can give control back to the executor. + // + // # Example + // + // ```cpp + // class MyThread : public nMatcha::Thread { + // virtual void threadFn() override { + // puts("Hello"); + // yield(); + // puts("World"); + // } + // }; + // ``` + // struct Thread { Thread(const Thread&) = delete; Thread& operator=(const Thread&) = delete; Thread(); virtual ~Thread() {} - virtual void threadFn() = 0; - - bool isFinished() const { - return mFinished; - } + bool isFinished() const; protected: void yield(); private: - static void entry(void* obj); + virtual void threadFn() = 0; + + static void entry(void* ctx); void* mStackPtr; bool mFinished; @@ -32,20 +51,34 @@ namespace nMatcha { const Executor* mExecutor; }; + // Helper interface to implement yielding for function objects. struct Yielder { virtual void yield() = 0; }; + // Utility class to create cooperative user threads from function objects. + // + // # Example + // + // ```cpp + // auto t = nMatcha::FnThread::make([](nMatcha::Yielder& y) { + // puts("Hello"); + // y.yield(); + // puts("World"); + // }); + // ``` + // struct FnThread : public Thread, public Yielder { using UserFn = std::function<void(Yielder&)>; + + // Factory method to create `FnThread` objects. static std::unique_ptr<Thread> make(UserFn f); private: + UserFn mUserFn; virtual void threadFn() override; virtual void yield() override; - UserFn mUserFn; - enum class CreatorToken {}; public: |