thread_safe_wrap.h 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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. #pragma once
  8. #include <utility>
  9. namespace base {
  10. template <typename T>
  11. class thread_safe_wrap {
  12. public:
  13. template <typename ...Args>
  14. thread_safe_wrap(Args &&...args) : _value(std::forward<Args>(args)...) {
  15. }
  16. template <typename Callback>
  17. auto with(Callback &&callback) {
  18. QMutexLocker lock(&_mutex);
  19. return callback(_value);
  20. }
  21. template <typename Callback>
  22. auto with(Callback &&callback) const {
  23. QMutexLocker lock(&_mutex);
  24. return callback(_value);
  25. }
  26. private:
  27. T _value;
  28. mutable QMutex _mutex;
  29. };
  30. template <typename T, template<typename...> typename Container = std::deque>
  31. class thread_safe_queue {
  32. public:
  33. template <typename ...Args>
  34. void emplace(Args &&...args) {
  35. _wrap.with([&](Container<T> &value) {
  36. value.emplace_back(std::forward<Args>(args)...);
  37. });
  38. }
  39. Container<T> take() {
  40. return _wrap.with([&](Container<T> &value) {
  41. return std::exchange(value, Container<T>());
  42. });
  43. }
  44. private:
  45. thread_safe_wrap<Container<T>> _wrap;
  46. };
  47. } // namespace base