| 1 | #include "fd.h" |
| 2 | #include <Rcpp.h> |
| 3 | #include <unistd.h> |
| 4 | #include <cstdlib> |
| 5 | #include <atomic> |
| 6 | #include <memory> |
| 7 | #include "tinycthread.h" |
| 8 | #include "later.h" |
| 9 | #include "callback_registry_table.h" |
| 10 | |
| 11 | class ThreadArgs { |
| 12 | public: |
| 13 | ThreadArgs( |
| 14 | int num_fds, |
| 15 | struct pollfd *fds, |
| 16 | double timeout, |
| 17 | int loop, |
| 18 | CallbackRegistryTable& table |
| 19 | ) |
| 20 | : timeout(createTimestamp(timeout)), |
| 21 | active(std::make_shared<std::atomic<bool>>(true)), |
| 22 | fds(std::vector<struct pollfd>(fds, fds + num_fds)), |
| 23 | results(std::vector<int>(num_fds)), |
| 24 | loop(loop), |
| 25 | registry(table.getRegistry(loop)) { |
| 26 | |
| 27 | if (registry == nullptr) |
| 28 | throw std::runtime_error("CallbackRegistry does not exist."); |
| 29 | |
| 30 | registry->fd_waits_incr(); |
| 31 | } |
| 32 | |
| 33 | ThreadArgs( |
| 34 | const Rcpp::Function& func, |
| 35 | int num_fds, |
| 36 | struct pollfd *fds, |
| 37 | double timeout, |
| 38 | int loop, |
| 39 | CallbackRegistryTable& table |
| 40 | ) : ThreadArgs(num_fds, fds, timeout, loop, table) { |
| 41 | callback = std::unique_ptr<Rcpp::Function>(new Rcpp::Function(func)); |
| 42 | } |
| 43 | |
| 44 | ThreadArgs( |
| 45 | void (*func)(int *, void *), |
| 46 | void *data, |
| 47 | int num_fds, |
| 48 | struct pollfd *fds, |
| 49 | double timeout, |
| 50 | int loop, |
| 51 | CallbackRegistryTable& table |
| 52 | ) : ThreadArgs(num_fds, fds, timeout, loop, table) { |
| 53 | callback_native = std::bind(func, std::placeholders::_1, data); |
| 54 | } |
| 55 | |
| 56 | ~ThreadArgs() { |
| 57 | registry->fd_waits_decr(); |
| 58 | } |
| 59 | |
| 60 | Timestamp timeout; |
| 61 | std::shared_ptr<std::atomic<bool>> active; |
| 62 | std::unique_ptr<Rcpp::Function> callback = nullptr; |
| 63 | std::function<void (int *)> callback_native = nullptr; |
| 64 | std::vector<struct pollfd> fds; |
| 65 | std::vector<int> results; |
| 66 | const int loop; |
| 67 | |
| 68 | private: |
| 69 | std::shared_ptr<CallbackRegistry> registry; |
| 70 | |
| 71 | static Timestamp createTimestamp(double timeout) { |
| 72 | if (timeout > 3e10) { |
| 73 | timeout = 3e10; // "1000 years ought to be enough for anybody" --Bill Gates |
| 74 | } else if (timeout < 0) { |
| 75 | timeout = 1; // curl_multi_timeout() uses -1 to denote a default we set at 1s |
| 76 | } |
| 77 | return Timestamp(timeout); |
| 78 | } |
| 79 | |
| 80 | }; |
| 81 | |
| 82 | static void later_callback(void *arg) { |
| 83 | |
| 84 | ASSERT_MAIN_THREAD() |
| 85 | |
| 86 | std::unique_ptr<ThreadArgs> args(static_cast<ThreadArgs *>(arg)); |
| 87 | bool still_active = true; |
| 88 | // atomic compare_exchange_strong: |
| 89 | // if args->active is true, it is changed to false (so future requests to fd_cancel return false) |
| 90 | // if args->active is false (cancelled), still_active is changed to false |
| 91 | args->active->compare_exchange_strong(still_active, false); |
| 92 | if (!still_active) |
| 93 | return; |
| 94 | if (args->callback != nullptr) { |
| 95 | Rcpp::LogicalVector results(args->results.begin(), args->results.end()); |
| 96 | (*args->callback)(results); |
| 97 | } else { |
| 98 | args->callback_native(args->results.data()); |
| 99 | } |
| 100 | |
| 101 | } |
| 102 | |
| 103 | // CONSIDER: if necessary to add method for HANDLES on Windows. Would be different code to SOCKETs. |
| 104 | // TODO: implement re-usable background thread. |
| 105 | static int wait_thread(void *arg) { |
| 106 | |
| 107 | tct_thrd_detach(tct_thrd_current()); |
| 108 | |
| 109 | std::unique_ptr<ThreadArgs> args(static_cast<ThreadArgs *>(arg)); |
| 110 | |
| 111 | int ready; |
| 112 | double waitFor = std::fmax(args->timeout.diff_secs(Timestamp()), 0); |
| 113 | do { |
| 114 | // Never wait for longer than ~1 second so we can check for cancellation |
| 115 | waitFor = std::fmin(waitFor, 1.024); |
| 116 | ready = LATER_POLL_FUNC(args->fds.data(), static_cast<LATER_NFDS_T>(args->fds.size()), static_cast<int>(waitFor * 1000)); |
| 117 | if (!args->active->load()) return 1; |
| 118 | if (ready) break; |
| 119 | } while ((waitFor = args->timeout.diff_secs(Timestamp())) > 0); |
| 120 | |
| 121 | if (ready > 0) { |
| 122 | for (std::size_t i = 0; i < args->fds.size(); i++) { |
| 123 | (args->results)[i] = (args->fds)[i].revents == 0 ? 0 : (args->fds)[i].revents & (POLLIN | POLLOUT) ? 1: NA_INTEGER; |
| 124 | } |
| 125 | } else if (ready < 0) { |
| 126 | std::fill(args->results.begin(), args->results.end(), NA_INTEGER); |
| 127 | } |
| 128 | |
| 129 | int loop_id = args->loop; |
| 130 | callbackRegistryTable.scheduleCallback(later_callback, static_cast<void *>(args.release()), 0, loop_id); |
| 131 | |
| 132 | return 0; |
| 133 | |
| 134 | } |
| 135 | |
| 136 | static SEXP execLater_fd_impl(const Rcpp::Function& callback, int num_fds, struct pollfd *fds, double timeout, int loop_id) { |
| 137 | |
| 138 | std::unique_ptr<ThreadArgs> args(new ThreadArgs(callback, num_fds, fds, timeout, loop_id, callbackRegistryTable)); |
| 139 | std::shared_ptr<std::atomic<bool>> active = args->active; |
| 140 | tct_thrd_t thr; |
| 141 | |
| 142 | if (tct_thrd_create(&thr, &wait_thread, static_cast<void *>(args.release())) != tct_thrd_success) |
| 143 | Rcpp::stop("Thread creation failed"); |
| 144 | |
| 145 | Rcpp::XPtr<std::shared_ptr<std::atomic<bool>>> xptr(new std::shared_ptr<std::atomic<bool>>(active), true); |
| 146 | return xptr; |
| 147 | |
| 148 | } |
| 149 | |
| 150 | // native version |
| 151 | static int execLater_fd_native(void (*func)(int *, void *), void *data, int num_fds, struct pollfd *fds, double timeout, int loop_id) { |
| 152 | |
| 153 | std::unique_ptr<ThreadArgs> args(new ThreadArgs(func, data, num_fds, fds, timeout, loop_id, callbackRegistryTable)); |
| 154 | tct_thrd_t thr; |
| 155 | |
| 156 | return tct_thrd_create(&thr, &wait_thread, static_cast<void *>(args.release())) != tct_thrd_success; |
| 157 | |
| 158 | } |
| 159 | |
| 160 | // [[Rcpp::export(rng = false)]] |
| 161 | Rcpp::RObject execLater_fd(Rcpp::Function callback, Rcpp::IntegerVector readfds, Rcpp::IntegerVector writefds, |
| 162 | Rcpp::IntegerVector exceptfds, Rcpp::NumericVector timeoutSecs, Rcpp::IntegerVector loop_id) { |
| 163 | |
| 164 | const int rfds = static_cast<int>(readfds.size()); |
| 165 | const int wfds = static_cast<int>(writefds.size()); |
| 166 | const int efds = static_cast<int>(exceptfds.size()); |
| 167 | const int num_fds = rfds + wfds + efds; |
| 168 | const double timeout = num_fds ? timeoutSecs[0] : 0; |
| 169 | const int loop = loop_id[0]; |
| 170 | |
| 171 | std::vector<struct pollfd> pollfds; |
| 172 | pollfds.reserve(num_fds); |
| 173 | struct pollfd pfd; |
| 174 | |
| 175 | for (int i = 0; i < rfds; i++) { |
| 176 | pfd.fd = readfds[i]; |
| 177 | pfd.events = POLLIN; |
| 178 | pfd.revents = 0; |
| 179 | pollfds.push_back(pfd); |
| 180 | } |
| 181 | for (int i = 0; i < wfds; i++) { |
| 182 | pfd.fd = writefds[i]; |
| 183 | pfd.events = POLLOUT; |
| 184 | pfd.revents = 0; |
| 185 | pollfds.push_back(pfd); |
| 186 | } |
| 187 | for (int i = 0; i < efds; i++) { |
| 188 | pfd.fd = exceptfds[i]; |
| 189 | pfd.events = 0; |
| 190 | pfd.revents = 0; |
| 191 | pollfds.push_back(pfd); |
| 192 | } |
| 193 | |
| 194 | return execLater_fd_impl(callback, num_fds, pollfds.data(), timeout, loop); |
| 195 | |
| 196 | } |
| 197 | |
| 198 | // [[Rcpp::export(rng = false)]] |
| 199 | Rcpp::LogicalVector fd_cancel(Rcpp::RObject xptr) { |
| 200 | |
| 201 | Rcpp::XPtr<std::shared_ptr<std::atomic<bool>>> active(xptr); |
| 202 | |
| 203 | bool cancelled = true; |
| 204 | // atomic compare_exchange_strong: |
| 205 | // if *active is true, *active is changed to false (successful cancel) |
| 206 | // if *active is false (already run or cancelled), cancelled is changed to false |
| 207 | (*active)->compare_exchange_strong(cancelled, false); |
| 208 | |
| 209 | return cancelled; |
| 210 | |
| 211 | } |
| 212 | |
| 213 | // Schedules a C function that takes a pointer to an integer array (provided by |
| 214 | // this function when calling back) and a void * argument, to execute on file |
| 215 | // descriptor readiness. Returns 0 upon success and 1 if creating the wait |
| 216 | // thread failed. NOTE: this is different to execLaterNative2() which returns 0 |
| 217 | // on failure. |
| 218 | extern "C" int execLaterFdNative(void (*func)(int *, void *), void *data, int num_fds, struct pollfd *fds, double timeoutSecs, int loop_id) { |
| 219 | ensureInitialized(); |
| 220 | return execLater_fd_native(func, data, num_fds, fds, timeoutSecs, loop_id); |
| 221 | } |