LIPH's C++ Codes
coroutine.h
Go to the documentation of this file.
1#ifndef LIPH_COROUTINE_H_
2#define LIPH_COROUTINE_H_
3
4// C++ version of https://github.com/cloudwu/coroutine
5
6#include "liph/macros.h"
7#ifdef OS_LINUX
8
9#include <ucontext.h>
10
11#include <cstddef>
12#include <cstring>
13#include <functional>
14#include <memory>
15#include <vector>
16
17namespace liph {
18
19class coroutine;
20
21class processor {
22public:
23 static const size_t STACKSIZE = 1024 * 1024; // 1M
24
25public:
26 int add(std::shared_ptr<coroutine> co); // return coroutine id, -1 on failure
27 void resume(int id);
28 void yield();
29 int status(int id) const;
30
31private:
32 static void run(processor *p);
33
34private:
35 char stack_[STACKSIZE];
36 ucontext_t main_;
37 int running_id_{-1};
38 std::vector<std::shared_ptr<coroutine> > co_list_;
39};
40
41class coroutine {
42public:
43 enum { DEAD = 0, READY = 1, RUNNING = 2, SUSPEND = 3 };
44
45 friend class processor;
46
47public:
48 coroutine(std::function<void(void *)> entry, void *user_data) : entry_(entry), user_data_(user_data) {}
49
50 int status() const { return status_; }
51
52private:
53 void save_stack(char *top);
54
55private:
56 std::function<void(void *)> entry_;
57 void *user_data_{nullptr};
58 ucontext_t ctx_;
59 ptrdiff_t cap_{0};
60 ptrdiff_t size_{0};
61 int status_{READY};
62 char *stack_{nullptr};
63};
64
65} // namespace liph
66
67#endif
68
69#endif // LIPH_COROUTINE_H_
Definition: algorithm.h:10