// // OwningLock.hpp // Nitro // // Created by Marc Rousavy on 30.07.24. // #pragma once namespace margelo::nitro { template class OwningReference; } #include "OwningReference.hpp" #include #include namespace margelo::nitro { /** * An `OwningLock` is a RAII instance that locks the given caller thread guaranteed safe access * to a `OwningReference`. * The `OwningReference` cannot be deleted while an `OwningLock` of it is alive. * * This is useful in JSI, because Hermes runs garbage collection on a separate Thread, * and the separate Thread can delete an `OwningReference` while it's still in use. * The `OwningLock` prevents exactly this problem by blocking the GC destructor until * the `OwningLock` is released. * * To create an `OwningLock`, simply call `lock()` on an `OwningReference`. */ template class OwningLock final { public: ~OwningLock() { _reference._mutex->unlock(); } OwningLock() = delete; OwningLock(const OwningLock&) = delete; OwningLock(OwningLock&&) = delete; private: explicit OwningLock(const OwningReference& reference) : _reference(reference) { _reference._mutex->lock(); } private: OwningReference _reference; private: friend class OwningReference; }; } // namespace margelo::nitro