diff --git a/client/wifi_lock.cpp b/client/wifi_lock.cpp index f9e5653b..15e21fca 100644 --- a/client/wifi_lock.cpp +++ b/client/wifi_lock.cpp @@ -58,19 +58,6 @@ void wifi_lock::print_wifi() spdlog::info("WifiLock low latency released"); } -void wifi_lock::acquire_wifi() -{ - std::lock_guard lock(mutex); - wifi_.call("acquire"); - print_wifi(); -} -void wifi_lock::release_wifi() -{ - std::lock_guard lock(mutex); - wifi_.call("release"); - print_wifi(); -} - void wifi_lock::print_multicast() { if (multicast_.call("isHeld")) @@ -79,30 +66,43 @@ void wifi_lock::print_multicast() spdlog::info("MulticastLock released"); } -void wifi_lock::acquire_multicast() -{ - std::lock_guard lock(mutex); - multicast_.call("acquire"); - print_multicast(); -} -void wifi_lock::release_multicast() -{ - std::lock_guard lock(mutex); - multicast_.call("release"); - print_multicast(); -} - std::shared_ptr wifi_lock::get_wifi_lock() { - acquire_wifi(); + std::lock_guard lock(mutex); + if (auto l = wifi_weak.lock()) + return l; + + wifi_.call("acquire"); + print_wifi(); + // The shared pointer has a separate reference counter: destructor only calls a method - return std::shared_ptr(this, [self = shared_from_this()](void *) { self->release_wifi(); }); + auto res = std::shared_ptr( + this, + [self = shared_from_this()](void *) { + std::lock_guard lock(self->mutex); + self->wifi_.call("release"); + self->print_wifi(); }); + wifi_weak = res; + return res; } std::shared_ptr wifi_lock::get_multicast_lock() { - acquire_multicast(); + std::lock_guard lock(mutex); + if (auto l = multicast_weak.lock()) + return l; + + multicast_.call("acquire"); + print_multicast(); + // The shared pointer has a separate reference counter: destructor only calls a method - return std::shared_ptr(this, [self = shared_from_this()](void *) { self->release_multicast(); }); + auto res = std::shared_ptr( + this, + [self = shared_from_this()](void *) { + std::lock_guard lock(self->mutex); + self->multicast_.call("release"); + self->print_multicast(); }); + multicast_weak = res; + return res; } #else diff --git a/client/wifi_lock.h b/client/wifi_lock.h index fb413780..1813b49d 100644 --- a/client/wifi_lock.h +++ b/client/wifi_lock.h @@ -34,11 +34,10 @@ class wifi_lock : public std::enable_shared_from_this wifi_lock(decltype(multicast_), decltype(wifi_)); void print_wifi(); - void acquire_wifi(); - void release_wifi(); void print_multicast(); - void acquire_multicast(); - void release_multicast(); + + std::weak_ptr multicast_weak; + std::weak_ptr wifi_weak; public: static std::shared_ptr make_wifi_lock(jobject activity);