crl_object_on_thread.cpp 852 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. // This file is part of Desktop App Toolkit,
  2. // a set of libraries for developing nice desktop applications.
  3. //
  4. // For license and copyright information please follow this link:
  5. // https://github.com/desktop-app/legal/blob/master/LEGAL
  6. //
  7. #include <crl/crl_object_on_thread.h>
  8. #include <crl/crl_fp_exceptions.h>
  9. #include <thread>
  10. namespace crl::details {
  11. thread_policy::thread_policy() {
  12. std::thread([=] { run(); }).detach();
  13. }
  14. void thread_policy::run() {
  15. toggle_fp_exceptions(true);
  16. while (true) {
  17. if (!_list.process()) {
  18. break;
  19. }
  20. _queued.clear();
  21. std::unique_lock<std::mutex> lock(_mutex);
  22. _variable.wait(lock, [=] { return !_list.empty(); });
  23. }
  24. }
  25. void thread_policy::wake_async() const {
  26. if (!_queued.test_and_set()) {
  27. std::unique_lock<std::mutex> lock(_mutex);
  28. _variable.notify_one();
  29. }
  30. }
  31. } // namespace crl::details