ScriptWatchdog.cpp 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. #include "ScriptWatchdog.h"
  2. #include "WallpaperEngine/Logging/ThreadGuard.h"
  3. using namespace WallpaperEngine::Scripting;
  4. namespace {
  5. // how late a runaway script is noticed at the most, on top of its budget
  6. constexpr std::chrono::milliseconds PollInterval { 100 };
  7. } // namespace
  8. ScriptWatchdog::ScriptWatchdog (v8::Isolate* isolate) : m_isolate (isolate) {
  9. this->m_thread
  10. = std::thread ([this] { WallpaperEngine::Logging::guardThread ("Script watchdog", [this] { this->run (); }); });
  11. }
  12. ScriptWatchdog::~ScriptWatchdog () {
  13. {
  14. const std::lock_guard lock (this->m_mutex);
  15. this->m_stop = true;
  16. }
  17. this->m_wake.notify_all ();
  18. this->m_thread.join ();
  19. }
  20. void ScriptWatchdog::begin (const std::chrono::milliseconds budget) {
  21. const std::lock_guard lock (this->m_mutex);
  22. this->m_deadline = std::chrono::steady_clock::now () + budget;
  23. this->m_armed = true;
  24. this->m_fired = false;
  25. }
  26. bool ScriptWatchdog::fired () {
  27. const std::lock_guard lock (this->m_mutex);
  28. return this->m_fired;
  29. }
  30. bool ScriptWatchdog::end () {
  31. const std::lock_guard lock (this->m_mutex);
  32. const bool fired = this->m_fired;
  33. this->m_armed = false;
  34. this->m_fired = false;
  35. return fired;
  36. }
  37. void ScriptWatchdog::run () {
  38. std::unique_lock lock (this->m_mutex);
  39. while (!this->m_stop) {
  40. this->m_wake.wait_for (lock, PollInterval, [this] { return this->m_stop; });
  41. // decided and done under the lock: a call that just ended (end ()) or began again can't be hit by a stale
  42. // decision
  43. if (this->m_armed && std::chrono::steady_clock::now () >= this->m_deadline) {
  44. this->m_armed = false;
  45. this->m_fired = true;
  46. this->m_isolate->TerminateExecution ();
  47. }
  48. }
  49. }