libcommunism
Userspace cooperative threading library
Cothread.h
Go to the documentation of this file.
1 #ifndef LIBCOMMUNISM_COTHREAD_H
2 #define LIBCOMMUNISM_COTHREAD_H
3 
4 #include <array>
5 #include <cstddef>
6 #include <cstdint>
7 #include <functional>
8 #include <span>
9 #include <string>
10 
14 namespace libcommunism {
15 struct CothreadImpl;
16 
24 class Cothread {
25  public:
27  using Entry = std::function<void()>;
28 
40  [[nodiscard]] static Cothread *Current();
41 
54  static void SetReturnHandler(const std::function<void(Cothread *)> &handler);
55 
60  static void ResetReturnHandler();
61 
85  Cothread(const Entry &entry, const size_t stackSize = 0);
86 
110  Cothread(const Entry &entry, std::span<uintptr_t> stack);
111 
119  ~Cothread();
120 
132  void switchTo();
133 
139  constexpr auto &getLabel() const {
140  return this->label;
141  }
142 
148  void setLabel(const std::string &newLabel) {
149  this->label = newLabel;
150  }
151 
158  size_t getStackSize() const;
159 
172  void *getStack() const;
173 
174  private:
181  Cothread(CothreadImpl *impl) : impl(impl) {}
182 
183  private:
185  std::string label{""};
186 
187  private:
188  CothreadImpl *impl{nullptr};
189 
190  static thread_local Cothread *gCurrent;
191 
199  std::array<uintptr_t, 32> implBuffer;
201  bool implBufferUsed{false};
202 };
203 }
204 
205 #endif
Instance of a single cooperative thread.
Definition: Cothread.h:24
static void SetReturnHandler(const std::function< void(Cothread *)> &handler)
Definition: Cothread.cpp:130
Cothread(const Entry &entry, const size_t stackSize=0)
Definition: Cothread.cpp:99
std::function< void()> Entry
Type alias for an entry point of a cothread.
Definition: Cothread.h:27
static Cothread * Current()
Definition: Cothread.cpp:117
size_t getStackSize() const
Definition: Cothread.cpp:148
constexpr auto & getLabel() const
Definition: Cothread.h:139
void setLabel(const std::string &newLabel)
Definition: Cothread.h:148
static void ResetReturnHandler()
Definition: Cothread.cpp:134
void * getStack() const
Definition: Cothread.cpp:144
Main namespace for the libcommunism library.
Definition: Common.h:11
Abstract interface for a platform implementation of cothreads.
Definition: CothreadImpl.h:18