// // OwningLock.hpp // Nitro // // Created by Marc Rousavy on 30.07.24. // #pragma once namespace margelo::nitro { template class BorrowingReference; } #include "BorrowingReference.hpp" #include #include namespace margelo::nitro { /** * An `OwningLock` is a RAII instance that locks the given caller thread guaranteed safe access * to a `BorrowingReference`. * The `BorrowingReference` 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 `BorrowingReference` 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 `BorrowingReference`. */ template class OwningLock final { private: explicit OwningLock(const BorrowingReference& reference) : _reference(reference) { _reference._state->mutex.lock(); } public: ~OwningLock() { _reference._state->mutex.unlock(); } OwningLock() = delete; OwningLock(const OwningLock&) = delete; OwningLock(OwningLock&&) = delete; private: BorrowingReference _reference; private: friend class BorrowingReference; }; } // namespace margelo::nitro