| 44 | |
| 45 | |
| 46 | void handle_async(struct ev_loop* loop, ev_async* _, int revents) |
| 47 | { |
| 48 | std::queue<lambda::function<void()>> run_functions; |
| 49 | synchronized (watchers_mutex) { |
| 50 | // Start all the new I/O watchers. |
| 51 | while (!watchers->empty()) { |
| 52 | ev_io* watcher = watchers->front(); |
| 53 | watchers->pop(); |
| 54 | ev_io_start(loop, watcher); |
| 55 | } |
| 56 | |
| 57 | // Swap the functions into a temporary queue so that we can invoke |
| 58 | // them outside of the mutex. |
| 59 | std::swap(run_functions, *functions); |
| 60 | } |
| 61 | |
| 62 | // Running the functions outside of the mutex reduces locking |
| 63 | // contention as these are arbitrary functions that can take a long |
| 64 | // time to execute. Doing this also avoids a deadlock scenario where |
| 65 | // (A) mutexes are acquired before calling `run_in_event_loop`, |
| 66 | // followed by locking (B) `watchers_mutex`. If we executed the |
| 67 | // functions inside the mutex, then the locking order violation |
| 68 | // would be this function acquiring the (B) `watchers_mutex` |
| 69 | // followed by the arbitrary function acquiring the (A) mutexes. |
| 70 | while (!run_functions.empty()) { |
| 71 | (run_functions.front())(); |
| 72 | run_functions.pop(); |
| 73 | } |
| 74 | } |
| 75 | |
| 76 | |
| 77 | void handle_shutdown(struct ev_loop* loop, ev_async* _, int revents) |