Commit e3565000fb7dfe168ecce084a930fdf9bdc86179
1 parent
d5ad0507
Add condition variable for event loop
Instead of busy looping event thread, use a condition variable that is notified every time a command is sent or received, or every 100 milliseconds anyway.
Showing
2 changed files
with
15 additions
and
0 deletions
src/redox.cpp
| @@ -101,6 +101,10 @@ void Redox::run_event_loop() { | @@ -101,6 +101,10 @@ void Redox::run_event_loop() { | ||
| 101 | while (!to_exit) { | 101 | while (!to_exit) { |
| 102 | process_queued_commands(); | 102 | process_queued_commands(); |
| 103 | ev_run(evloop, EVRUN_NOWAIT); | 103 | ev_run(evloop, EVRUN_NOWAIT); |
| 104 | + | ||
| 105 | + // Wait until notified, or check every 100 milliseconds | ||
| 106 | + unique_lock<mutex> ul(loop_waiter_lock); | ||
| 107 | + loop_waiter.wait_for(ul, chrono::milliseconds(100)); | ||
| 104 | } | 108 | } |
| 105 | 109 | ||
| 106 | cout << "[INFO] Stop signal detected." << endl; | 110 | cout << "[INFO] Stop signal detected." << endl; |
| @@ -177,6 +181,9 @@ void Redox::command_callback(redisAsyncContext *ctx, void *r, void *privdata) { | @@ -177,6 +181,9 @@ void Redox::command_callback(redisAsyncContext *ctx, void *r, void *privdata) { | ||
| 177 | 181 | ||
| 178 | // Increment the Redox object command counter | 182 | // Increment the Redox object command counter |
| 179 | rdx->cmd_count++; | 183 | rdx->cmd_count++; |
| 184 | + | ||
| 185 | + // Notify to check the event loop | ||
| 186 | + rdx->loop_waiter.notify_one(); | ||
| 180 | } | 187 | } |
| 181 | 188 | ||
| 182 | /** | 189 | /** |
| @@ -191,6 +198,10 @@ bool Redox::submit_to_server(Command<ReplyT>* c) { | @@ -191,6 +198,10 @@ bool Redox::submit_to_server(Command<ReplyT>* c) { | ||
| 191 | c->invoke_error(REDOX_SEND_ERROR); | 198 | c->invoke_error(REDOX_SEND_ERROR); |
| 192 | return false; | 199 | return false; |
| 193 | } | 200 | } |
| 201 | + | ||
| 202 | + // Notify to check the event loop | ||
| 203 | + c->rdx->loop_waiter.notify_one(); | ||
| 204 | + | ||
| 194 | return true; | 205 | return true; |
| 195 | } | 206 | } |
| 196 | 207 |
src/redox.hpp
| @@ -187,6 +187,10 @@ private: | @@ -187,6 +187,10 @@ private: | ||
| 187 | std::mutex exit_waiter_lock; | 187 | std::mutex exit_waiter_lock; |
| 188 | std::condition_variable exit_waiter; | 188 | std::condition_variable exit_waiter; |
| 189 | 189 | ||
| 190 | + // Condition variable to check the event loop | ||
| 191 | + std::condition_variable loop_waiter; | ||
| 192 | + std::mutex loop_waiter_lock; | ||
| 193 | + | ||
| 190 | // Maps of each Command, fetchable by the unique ID number | 194 | // Maps of each Command, fetchable by the unique ID number |
| 191 | std::unordered_map<long, Command<redisReply*>*> commands_redis_reply; | 195 | std::unordered_map<long, Command<redisReply*>*> commands_redis_reply; |
| 192 | std::unordered_map<long, Command<std::string>*> commands_string_r; | 196 | std::unordered_map<long, Command<std::string>*> commands_string_r; |