Add ThreadBackgroundSleep helper class

This commit is contained in:
2023-08-18 23:26:11 +02:00
parent aa0f1e7967
commit 7e3aae1681
2 changed files with 81 additions and 0 deletions

View File

@@ -0,0 +1,47 @@
/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
#include "ThreadBackgroundSleep.hpp"
#include "Logger.hpp"
#include "AppEvents.hpp"
namespace openVulkanoCpp
{
ThreadBackgroundSleep ThreadBackgroundSleep::INSTANCE;
ThreadBackgroundSleep::ThreadBackgroundSleep()
{
m_resignHandler = AppEvents::OnWillResignActive += [this]() { m_inBackground = true; };
m_resumeHandler = AppEvents::OnDidBecomeActive += [this]() { Resume(); };
}
ThreadBackgroundSleep::~ThreadBackgroundSleep()
{
AppEvents::OnWillResignActive -= m_resignHandler;
AppEvents::OnDidBecomeActive -= m_resumeHandler;
Resume();
}
void ThreadBackgroundSleep::Resume()
{
{
std::unique_lock lock(m_mutex);
m_inBackground = false;
}
m_condVar.notify_all();
}
void ThreadBackgroundSleep::CheckForBackground(std::string_view taskName)
{
if (m_inBackground)
{
Logger::MANAGER->info("Sleep {}, because app has been sent to background.", taskName);
std::unique_lock l(m_mutex);
m_condVar.wait(l, [this]{ return !m_inBackground; });
Logger::MANAGER->info("Resume {}, app is no longer in background.", taskName);
}
}
}

View File

@@ -0,0 +1,34 @@
/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
#include <condition_variable>
#include <mutex>
#include <string_view>
namespace openVulkanoCpp
{
class IEventHandler;
class ThreadBackgroundSleep final
{
std::mutex m_mutex;
std::condition_variable m_condVar;
bool m_inBackground = false;
IEventHandler* m_resignHandler = nullptr;
IEventHandler* m_resumeHandler = nullptr;
public:
static ThreadBackgroundSleep INSTANCE;
ThreadBackgroundSleep();
~ThreadBackgroundSleep();
void Resume();
void CheckForBackground(std::string_view taskName);
};
}