libcommunism
Userspace cooperative threading library
UContext.h
Go to the documentation of this file.
1 #ifndef ARCH_UCONTEXT_UCONTEXT_H
2 #define ARCH_UCONTEXT_UCONTEXT_H
3 
4 #include "CothreadPrivate.h"
5 #include "CothreadImpl.h"
6 
7 #include <array>
8 #include <cstddef>
9 #include <memory>
10 #include <mutex>
11 #include <unordered_map>
12 
13 #define _XOPEN_SOURCE
14 #include <ucontext.h>
15 
16 namespace libcommunism::internal {
33 class UContext final: public CothreadImpl {
35 
36  public:
37  UContext(const Entry &entry, const size_t stackSize = 0);
38  UContext(const Entry &entry, std::span<uintptr_t> stack);
39  UContext(std::span<uintptr_t> stack) : CothreadImpl(stack) {}
40  ~UContext();
41 
42  void switchTo(CothreadImpl *from) override;
43 
44  private:
48  struct Context {
50  Cothread::Entry entry;
51 
53  Context(const Cothread::Entry &_entry) : entry(_entry) {}
54  };
55 
67  static ucontext_t *ContextFor(CothreadImpl *thread) {
68  return reinterpret_cast<ucontext_t *>(static_cast<UContext *>(thread)->stack.data());
69  }
70 
71  static void AllocMainCothread();
72  static void Prepare(UContext *thread, const Cothread::Entry &entry);
73  static void EntryStub(int id);
74  static void InvokeCothreadDidReturnHandler(Cothread *from);
75 
76  public:
86  static constexpr const size_t kStackAlignment{64};
87 
94  static constexpr const size_t kMainStackSize{128};
95 
100  static constexpr const size_t kDefaultStackSize{sizeof(uintptr_t) * 0x10000};
101 
102  private:
114  static thread_local std::array<uintptr_t, kMainStackSize> gMainStack;
115 
124  static std::unordered_map<int, std::unique_ptr<Context>> gContextInfo;
125 
130  static std::mutex gContextInfoLock;
131 
135  static int gContextNextId;
136 
137  private:
139  bool ownsStack{false};
140 };
141 }
142 
143 
144 #endif
std::function< void()> Entry
Type alias for an entry point of a cothread.
Definition: Cothread.h:27
Implementation of context switching that uses the C library's setcontext() methods.
Definition: UContext.h:33
UContext(const Entry &entry, const size_t stackSize=0)
Definition: UContext.cpp:37
static constexpr const size_t kStackAlignment
Definition: UContext.h:86
void switchTo(CothreadImpl *from) override
Definition: UContext.cpp:180
UContext(std::span< uintptr_t > stack)
Definition: UContext.h:39
static constexpr const size_t kDefaultStackSize
Definition: UContext.h:100
static constexpr const size_t kMainStackSize
Definition: UContext.h:94
Implementation details (including architecture/platform specific code) for the library.
Definition: Common.h:11
CothreadImpl * AllocKernelThreadWrapper()
Definition: Common.cpp:134
Abstract interface for a platform implementation of cothreads.
Definition: CothreadImpl.h:18
CothreadImpl(const Cothread::Entry &entry, const size_t stackSize=0)
Definition: CothreadImpl.h:29
std::span< uintptr_t > stack
Stack used by this cothread, if any.
Definition: CothreadImpl.h:88