X-Git-Url: http://plrg.eecs.uci.edu/git/?p=folly.git;a=blobdiff_plain;f=folly%2FSingleton-inl.h;h=a56db30ea89a39b76f1174298bef1ff543e1135b;hp=c853da65053aa984d709590008940168284c5099;hb=afde52ff7655ba79759eafdbee14b3fe47428fce;hpb=d58181e677965b609be89b49ed7fbc4e78bf70b5 diff --git a/folly/Singleton-inl.h b/folly/Singleton-inl.h index c853da65..a56db30e 100644 --- a/folly/Singleton-inl.h +++ b/folly/Singleton-inl.h @@ -1,5 +1,5 @@ /* - * Copyright 2015 Facebook, Inc. + * Copyright 2015-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,18 +21,40 @@ namespace detail { template template SingletonHolder& SingletonHolder::singleton() { - static auto entry = new SingletonHolder( - {typeid(T), typeid(Tag)}, - *SingletonVault::singleton()); + /* library-local */ static auto entry = + createGlobal, std::pair>([]() { + return new SingletonHolder({typeid(T), typeid(Tag)}, + *SingletonVault::singleton()); + }); return *entry; } +[[noreturn]] void singletonWarnDoubleRegistrationAndAbort( + const TypeDescriptor& type); + template void SingletonHolder::registerSingleton(CreateFunc c, TeardownFunc t) { std::lock_guard entry_lock(mutex_); if (state_ != SingletonHolderState::NotRegistered) { - throw std::logic_error("Double registration"); + /* Possible causes: + * + * You have two instances of the same + * folly::Singleton. Probably because you define the + * singleton in a header included in multiple places? In general, + * folly::Singleton shouldn't be in the header, only off in some + * anonymous namespace in a cpp file. Code needing the singleton + * will find it when that code references folly::Singleton. + * + * Alternatively, you could have 2 singletons with the same type + * defined with a different name in a .cpp (source) file. For + * example: + * + * Singleton a([] { return new int(3); }); + * Singleton b([] { return new int(4); }); + * + */ + singletonWarnDoubleRegistrationAndAbort(type()); } create_ = std::move(c); @@ -44,9 +66,20 @@ void SingletonHolder::registerSingleton(CreateFunc c, TeardownFunc t) { template void SingletonHolder::registerSingletonMock(CreateFunc c, TeardownFunc t) { if (state_ == SingletonHolderState::NotRegistered) { - throw std::logic_error("Registering mock before singleton was registered"); + detail::singletonWarnRegisterMockEarlyAndAbort(type()); + } + if (state_ == SingletonHolderState::Living) { + destroyInstance(); + } + + { + auto creationOrder = vault_.creationOrder_.wlock(); + + auto it = std::find(creationOrder->begin(), creationOrder->end(), type()); + if (it != creationOrder->end()) { + creationOrder->erase(it); + } } - destroyInstance(); std::lock_guard entry_lock(mutex_); @@ -56,14 +89,14 @@ void SingletonHolder::registerSingletonMock(CreateFunc c, TeardownFunc t) { template T* SingletonHolder::get() { - if (LIKELY(state_ == SingletonHolderState::Living)) { + if (LIKELY(state_.load(std::memory_order_acquire) == + SingletonHolderState::Living)) { return instance_ptr_; } createInstance(); if (instance_weak_.expired()) { - throw std::runtime_error( - "Raw pointer to a singleton requested after its destruction."); + detail::singletonThrowGetInvokedAfterDestruction(type()); } return instance_ptr_; @@ -71,7 +104,8 @@ T* SingletonHolder::get() { template std::weak_ptr SingletonHolder::get_weak() { - if (UNLIKELY(state_ != SingletonHolderState::Living)) { + if (UNLIKELY(state_.load(std::memory_order_acquire) != + SingletonHolderState::Living)) { createInstance(); } @@ -79,8 +113,23 @@ std::weak_ptr SingletonHolder::get_weak() { } template -TypeDescriptor SingletonHolder::type() { - return type_; +std::shared_ptr SingletonHolder::try_get() { + if (UNLIKELY(state_.load(std::memory_order_acquire) != + SingletonHolderState::Living)) { + createInstance(); + } + + return instance_weak_.lock(); +} + +template +folly::ReadMostlySharedPtr SingletonHolder::try_get_fast() { + if (UNLIKELY(state_.load(std::memory_order_acquire) != + SingletonHolderState::Living)) { + createInstance(); + } + + return instance_weak_fast_.lock(); } template @@ -88,89 +137,105 @@ bool SingletonHolder::hasLiveInstance() { return !instance_weak_.expired(); } +template +void SingletonHolder::preDestroyInstance( + ReadMostlyMainPtrDeleter<>& deleter) { + instance_copy_ = instance_; + deleter.add(std::move(instance_)); +} + template void SingletonHolder::destroyInstance() { state_ = SingletonHolderState::Dead; instance_.reset(); + instance_copy_.reset(); if (destroy_baton_) { - auto wait_result = destroy_baton_->timed_wait( - std::chrono::steady_clock::now() + kDestroyWaitTime); - if (!wait_result) { + constexpr std::chrono::seconds kDestroyWaitTime{5}; + auto last_reference_released = + destroy_baton_->try_wait_for(kDestroyWaitTime); + if (last_reference_released) { + teardown_(instance_ptr_); + } else { print_destructor_stack_trace_->store(true); - LOG(ERROR) << "Singleton of type " << type_.name() << " has a " - << "living reference at destroyInstances time; beware! Raw " - << "pointer is " << instance_ptr_ << ". It is very likely " - << "that some other singleton is holding a shared_ptr to it. " - << "Make sure dependencies between these singletons are " - << "properly defined."; + detail::singletonWarnDestroyInstanceLeak(type(), instance_ptr_); } } } template -SingletonHolder::SingletonHolder(TypeDescriptor type__, - SingletonVault& vault) : - type_(type__), vault_(vault) { +SingletonHolder::SingletonHolder( + TypeDescriptor typeDesc, + SingletonVault& vault) + : SingletonHolderBase(typeDesc), vault_(vault) {} + +template +bool SingletonHolder::creationStarted() { + // If alive, then creation was of course started. + // This is flipped after creating_thread_ was set, and before it was reset. + if (state_.load(std::memory_order_acquire) == SingletonHolderState::Living) { + return true; + } + + // Not yet built. Is it currently in progress? + if (creating_thread_.load(std::memory_order_acquire) != std::thread::id()) { + return true; + } + + return false; } template void SingletonHolder::createInstance() { - // There's no synchronization here, so we may not see the current value - // for creating_thread if it was set by other thread, but we only care about - // it if it was set by current thread anyways. - if (creating_thread_ == std::this_thread::get_id()) { - throw std::out_of_range(std::string("circular singleton dependency: ") + - type_.name()); + if (creating_thread_.load(std::memory_order_acquire) == + std::this_thread::get_id()) { + detail::singletonWarnCreateCircularDependencyAndAbort(type()); } std::lock_guard entry_lock(mutex_); - if (state_ == SingletonHolderState::Living) { + if (state_.load(std::memory_order_acquire) == SingletonHolderState::Living) { return; } - if (state_ == SingletonHolderState::NotRegistered) { - throw std::out_of_range("Creating instance for unregistered singleton"); + if (state_.load(std::memory_order_acquire) == + SingletonHolderState::NotRegistered) { + detail::singletonWarnCreateUnregisteredAndAbort(type()); } - if (state_ == SingletonHolderState::Living) { + if (state_.load(std::memory_order_acquire) == SingletonHolderState::Living) { return; } - creating_thread_ = std::this_thread::get_id(); + SCOPE_EXIT { + // Clean up creator thread when complete, and also, in case of errors here, + // so that subsequent attempts don't think this is still in the process of + // being built. + creating_thread_.store(std::thread::id(), std::memory_order_release); + }; + + creating_thread_.store(std::this_thread::get_id(), std::memory_order_release); - RWSpinLock::ReadHolder rh(&vault_.stateMutex_); - if (vault_.state_ == SingletonVault::SingletonVaultState::Quiescing) { - creating_thread_ = std::thread::id(); + auto state = vault_.state_.rlock(); + if (vault_.type_ != SingletonVault::Type::Relaxed && + !state->registrationComplete) { + detail::singletonWarnCreateBeforeRegistrationCompleteAndAbort(type()); + } + if (state->state == detail::SingletonVaultState::Type::Quiescing) { return; } auto destroy_baton = std::make_shared>(); auto print_destructor_stack_trace = std::make_shared>(false); - auto teardown = teardown_; - auto type_name = type_.name(); // Can't use make_shared -- no support for a custom deleter, sadly. - instance_ = std::shared_ptr( - create_(), - [destroy_baton, print_destructor_stack_trace, teardown, type_name] - (T* instance_ptr) mutable { - teardown(instance_ptr); - destroy_baton->post(); - if (print_destructor_stack_trace->load()) { - std::string output = "Singleton " + type_name + " was destroyed.\n"; - - auto stack_trace_getter = SingletonVault::stackTraceGetter().load(); - auto stack_trace = stack_trace_getter ? stack_trace_getter() : ""; - if (stack_trace.empty()) { - output += "Failed to get destructor stack trace."; - } else { - output += "Destructor stack trace:\n"; - output += stack_trace; + std::shared_ptr instance( + create_(), + [ destroy_baton, print_destructor_stack_trace, type = type() ]( + T*) mutable { + destroy_baton->post(); + if (print_destructor_stack_trace->load()) { + detail::singletonPrintDestructionStackTrace(type); } - - LOG(ERROR) << output; - } - }); + }); // We should schedule destroyInstances() only after the singleton was // created. This will ensure it will be destroyed before singletons, @@ -178,22 +243,21 @@ void SingletonHolder::createInstance() { // constructor SingletonVault::scheduleDestroyInstances(); - instance_weak_ = instance_; - instance_ptr_ = instance_.get(); - creating_thread_ = std::thread::id(); + instance_weak_ = instance; + instance_ptr_ = instance.get(); + instance_.reset(std::move(instance)); + instance_weak_fast_ = instance_; + destroy_baton_ = std::move(destroy_baton); print_destructor_stack_trace_ = std::move(print_destructor_stack_trace); // This has to be the last step, because once state is Living other threads // may access instance and instance_weak w/o synchronization. - state_.store(SingletonHolderState::Living); + state_.store(SingletonHolderState::Living, std::memory_order_release); - { - RWSpinLock::WriteHolder wh(&vault_.mutex_); - vault_.creation_order_.push_back(type_); - } + vault_.creationOrder_.wlock()->push_back(type()); } -} +} // namespace detail -} +} // namespace folly