|
8 | 8 |
|
9 | 9 | #include <gloo/transport/tcp/loop.h> |
10 | 10 |
|
| 11 | +#include <fcntl.h> |
11 | 12 | #include <string.h> |
12 | 13 | #include <unistd.h> |
13 | 14 |
|
@@ -40,10 +41,69 @@ namespace gloo { |
40 | 41 | namespace transport { |
41 | 42 | namespace tcp { |
42 | 43 |
|
| 44 | +Deferrables::Deferrables() { |
| 45 | + std::array<int, 2> fds; |
| 46 | + auto rv = pipe2(fds.data(), O_NONBLOCK); |
| 47 | + GLOO_ENFORCE_NE(rv, -1, "pipe: ", strerror(errno)); |
| 48 | + rfd_ = fds[0]; |
| 49 | + wfd_ = fds[1]; |
| 50 | +} |
| 51 | + |
| 52 | +Deferrables::~Deferrables() { |
| 53 | + close(rfd_); |
| 54 | + close(wfd_); |
| 55 | +} |
| 56 | + |
| 57 | +void Deferrables::defer(function_t fn) { |
| 58 | + std::lock_guard<std::mutex> guard(mutex_); |
| 59 | + functions_.push_back(std::move(fn)); |
| 60 | + |
| 61 | + // Write byte to pipe to make epoll(2) wake up. |
| 62 | + if (!triggered_) { |
| 63 | + for (;;) { |
| 64 | + char byte = 0; |
| 65 | + auto rv = write(wfd_, &byte, sizeof(byte)); |
| 66 | + if (rv == -1 && errno == EINTR) { |
| 67 | + continue; |
| 68 | + } |
| 69 | + GLOO_ENFORCE_NE(rv, -1, "write: ", strerror(errno)); |
| 70 | + break; |
| 71 | + } |
| 72 | + triggered_ = true; |
| 73 | + } |
| 74 | +} |
| 75 | + |
| 76 | +void Deferrables::handleEvents(int /* unused */) { |
| 77 | + decltype(functions_) localFunctions; |
| 78 | + |
| 79 | + { |
| 80 | + std::lock_guard<std::mutex> guard(mutex_); |
| 81 | + std::swap(localFunctions, functions_); |
| 82 | + |
| 83 | + // Read byte from pipe to drain it. |
| 84 | + for (;;) { |
| 85 | + char byte = 0; |
| 86 | + auto rv = read(rfd_, &byte, sizeof(byte)); |
| 87 | + if (rv == -1 && errno == EINTR) { |
| 88 | + continue; |
| 89 | + } |
| 90 | + GLOO_ENFORCE_NE(rv, -1, "read: ", strerror(errno)); |
| 91 | + break; |
| 92 | + } |
| 93 | + triggered_ = false; |
| 94 | + } |
| 95 | + |
| 96 | + // Execute deferred functions. |
| 97 | + for (auto fn : localFunctions) { |
| 98 | + fn(); |
| 99 | + } |
| 100 | +} |
| 101 | + |
43 | 102 | Loop::Loop() { |
44 | 103 | fd_ = epoll_create(1); |
45 | 104 | GLOO_ENFORCE_NE(fd_, -1, "epoll_create: ", strerror(errno)); |
46 | 105 | loop_.reset(new std::thread(&Loop::run, this)); |
| 106 | + registerDescriptor(deferrables_.rfd_, EPOLLIN, &deferrables_); |
47 | 107 | } |
48 | 108 |
|
49 | 109 | Loop::~Loop() { |
@@ -81,6 +141,10 @@ void Loop::unregisterDescriptor(int fd, Handler* h) { |
81 | 141 | } |
82 | 142 | } |
83 | 143 |
|
| 144 | +void Loop::defer(std::function<void()> fn) { |
| 145 | + deferrables_.defer(std::move(fn)); |
| 146 | +} |
| 147 | + |
84 | 148 | void Loop::run() { |
85 | 149 | std::array<struct epoll_event, capacity_> events; |
86 | 150 | int nfds; |
|
0 commit comments