From 2c4330e7c01cf404406dd3380e64304460b29b02 Mon Sep 17 00:00:00 2001 From: johannst Date: Mon, 5 Oct 2020 23:03:03 +0200 Subject: added doc on thread & executor --- lib/thread.h | 49 +++++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 41 insertions(+), 8 deletions(-) (limited to 'lib/thread.h') 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; + + // Factory method to create `FnThread` objects. static std::unique_ptr make(UserFn f); private: + UserFn mUserFn; virtual void threadFn() override; virtual void yield() override; - UserFn mUserFn; - enum class CreatorToken {}; public: -- cgit v1.2.3