/* * WiVRn VR streaming * Copyright (C) 2024 Guillaume Meunier * Copyright (C) 2024 Patrick Nicolas * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #pragma once #include #include template class thread_safe_notifyable; template class locked { friend class thread_safe_notifyable; T & value; std::unique_lock lock; public: locked(T & value, Mutex & mutex) : value(value), lock(mutex) {} T * operator->() { return &value; } const T * operator->() const { return &value; } T & operator*() { return value; } const T & operator*() const { return value; } }; template class thread_safe { T value; Mutex mutex; public: template thread_safe(Args &&... args) : value(std::forward(args)...) {} [[nodiscard]] locked lock() { return locked(value, mutex); } T & get_unsafe() { return value; } const T & get_unsafe() const { return value; } }; template class locked_notifiable { friend class thread_safe_notifyable; T & value; std::unique_lock lock; std::condition_variable & cv; public: locked_notifiable(T & value, std::mutex & mutex, std::condition_variable & cv) : value(value), lock(mutex), cv(cv) {} T * operator->() { return &value; } const T * operator->() const { return &value; } T & operator*() { return value; } const T & operator*() const { return value; } void notify_one() noexcept { cv.notify_one(); } void notify_all() noexcept { cv.notify_all(); } void wait() { cv.wait(lock); } template void wait(Predicate && pred) { cv.wait(lock, std::forward(pred)); } template std::cv_status wait_for(const std::chrono::duration & rel_time) { return cv.wait_for(lock, rel_time); } template bool wait_for(const std::chrono::duration & rel_time, Predicate pred) { return cv.wait_for(lock, rel_time, pred); } template std::cv_status wait_until(const std::chrono::time_point & abs_time) { return cv.wait_until(lock, abs_time); } template bool wait_until(const std::chrono::time_point & abs_time, Predicate pred) { return cv.wait_until(lock, abs_time, pred); } }; template class thread_safe_notifyable : public thread_safe { T value; std::mutex mutex; std::condition_variable cv; public: template thread_safe_notifyable(Args &&... args) : thread_safe(std::forward(args)...) {} locked_notifiable lock() { return locked_notifiable(value, mutex, cv); } };