aboutsummaryrefslogtreecommitdiff
path: root/lib/thread.h
diff options
context:
space:
mode:
authorjohannst <johannes.stoelp@gmail.com>2020-10-05 23:03:03 +0200
committerjohannst <johannes.stoelp@gmail.com>2020-10-05 23:03:03 +0200
commit2c4330e7c01cf404406dd3380e64304460b29b02 (patch)
tree588bbbd660e16c45d3578fea988b9566cf9b3387 /lib/thread.h
parentabba364fb3b8871a2baac7779b0850b3bdc479b0 (diff)
downloadmatcha-threads-2c4330e7c01cf404406dd3380e64304460b29b02.tar.gz
matcha-threads-2c4330e7c01cf404406dd3380e64304460b29b02.zip
added doc on thread & executor
Diffstat (limited to 'lib/thread.h')
-rw-r--r--lib/thread.h49
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: