-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.cpp
57 lines (50 loc) · 1.07 KB
/
main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include <iostream>
#include "coroutine_stuff.h"
#include "io_stuff.h"
void SetToNonBlocking(int socket) {
int flags;
assert((flags = fcntl(socket, F_GETFL, 0)) >= 0);
assert(fcntl(socket, F_SETFL, flags | O_NONBLOCK) >= 0) ;
}
template<typename T>
void Go(T&& t) {
TCoroutine coroutine(t);
coroutine.Go();
}
class TAsyncAcceptor {
TAcceptor Acceptor;
public:
TAsyncAcceptor(int port)
: Acceptor(port) {
SetToNonBlocking(Acceptor.GetSocket());
}
int GetSocket() const {
return Acceptor.GetSocket();
}
TSocket Accept() {
try {
return Acceptor.Accept();
} catch(const TWouldBlockException&) {
Yield();
return Acceptor.Accept();
}
}
};
int main() {
TEpoll epoll;
TCoroutine coroutine([&epoll](TCoroutine* me) {
TAsyncAcceptor acceptor(1234);
TCallback callback([me]() {
me->Go();
});
epoll.Add(acceptor.GetSocket(), &callback);
for (;;) {
TSocket socket = acceptor.Accept();
socket.Write("Hello, world!");
}
});
coroutine.Go();
for (;;) {
epoll.Wait();
}
}