Commit e3565000fb7dfe168ecce084a930fdf9bdc86179

Authored by Hayk Martirosyan
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 101 while (!to_exit) {
102 102 process_queued_commands();
103 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 110 cout << "[INFO] Stop signal detected." << endl;
... ... @@ -177,6 +181,9 @@ void Redox::command_callback(redisAsyncContext *ctx, void *r, void *privdata) {
177 181  
178 182 // Increment the Redox object command counter
179 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&lt;ReplyT&gt;* c) {
191 198 c->invoke_error(REDOX_SEND_ERROR);
192 199 return false;
193 200 }
  201 +
  202 + // Notify to check the event loop
  203 + c->rdx->loop_waiter.notify_one();
  204 +
194 205 return true;
195 206 }
196 207  
... ...
src/redox.hpp
... ... @@ -187,6 +187,10 @@ private:
187 187 std::mutex exit_waiter_lock;
188 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 194 // Maps of each Command, fetchable by the unique ID number
191 195 std::unordered_map<long, Command<redisReply*>*> commands_redis_reply;
192 196 std::unordered_map<long, Command<std::string>*> commands_string_r;
... ...