Skip to content

Commit

Permalink
ClientSession can be woken up in order to destruct faster (closes #20)
Browse files Browse the repository at this point in the history
The way that the ClientSession background thread worked before was that it
unconditionally slept for m_check_interval to throttle the check events. This
works fine during normal execution, but it's a big problem for destruction: the
destructor correctly joins the thread and waits for it to finish, but that means
that the destructor can take up to m_check_interval seconds to execute. This is
not ideal: the destructor runs when the program shuts down, which can mean that
the ClientSession can essentially "lock up" shutdown for a long time without
doing any work.

The fix is to not use unconditional sleep, but to use a std::condition_variable
instead: the condition variable can sleep for a given number of time just like
std::this_thread::sleep_for, but it can also be woken up if needed. This change
wakes the thread up when calling ClientSession::stop(), and the condition
variable reads m_is_running to figure out if it should wake up and exit. This
change makes it so that ClientSession::stop() (and therefore the destructor)
finishes (essentially) instantly, regardless of the value for m_check_interval.
  • Loading branch information
OskarSigvardsson committed Feb 2, 2021
1 parent 08e762a commit 9714863
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 1 deletion.
9 changes: 8 additions & 1 deletion src/client_session.cpp
Expand Up @@ -74,6 +74,7 @@ void ClientSession::stop() {
unique_lock<mutex> locker(this->m_run_check);
if (this->m_is_running == true) {
this->m_is_running = false;
m_monitor.notify_one();
locker.unlock();
this->m_daemon_thread.join();
} else {
Expand Down Expand Up @@ -107,7 +108,13 @@ bool ClientSession::get_is_background() {

void ClientSession::run() {
do {
this_thread::sleep_for(chrono::milliseconds(this->m_check_interval));
{
unique_lock<mutex> guard(this->m_run_check);

m_monitor.wait_for(guard, chrono::milliseconds(this->m_check_interval), [&] {
return !this->m_is_running;
});
}

unsigned long long check_time = Utils::get_unix_epoch_ms();
unsigned long long range = this->m_is_background ? this->m_background_timeout : this->m_foreground_timeout;
Expand Down
1 change: 1 addition & 0 deletions src/client_session.hpp
Expand Up @@ -58,6 +58,7 @@ class ClientSession {

// Daemon
thread m_daemon_thread;
condition_variable m_monitor;
mutex m_run_check;
mutex m_safe_get;
bool m_is_running;
Expand Down

0 comments on commit 9714863

Please sign in to comment.