michael@0: // Copyright (c) 2011 The Chromium Authors. All rights reserved. michael@0: // Use of this source code is governed by a BSD-style license that can be michael@0: // found in the LICENSE file. michael@0: michael@0: #include "base/lazy_instance.h" michael@0: michael@0: #include "base/at_exit.h" michael@0: #include "base/atomicops.h" michael@0: #include "base/basictypes.h" michael@0: #include "base/threading/platform_thread.h" michael@0: #include "base/third_party/dynamic_annotations/dynamic_annotations.h" michael@0: michael@0: namespace base { michael@0: namespace internal { michael@0: michael@0: // TODO(joth): This function could be shared with Singleton, in place of its michael@0: // WaitForInstance() call. michael@0: bool NeedsLazyInstance(subtle::AtomicWord* state) { michael@0: // Try to create the instance, if we're the first, will go from 0 to michael@0: // kLazyInstanceStateCreating, otherwise we've already been beaten here. michael@0: // The memory access has no memory ordering as state 0 and michael@0: // kLazyInstanceStateCreating have no associated data (memory barriers are michael@0: // all about ordering of memory accesses to *associated* data). michael@0: if (subtle::NoBarrier_CompareAndSwap(state, 0, michael@0: kLazyInstanceStateCreating) == 0) michael@0: // Caller must create instance michael@0: return true; michael@0: michael@0: // It's either in the process of being created, or already created. Spin. michael@0: // The load has acquire memory ordering as a thread which sees michael@0: // state_ == STATE_CREATED needs to acquire visibility over michael@0: // the associated data (buf_). Pairing Release_Store is in michael@0: // CompleteLazyInstance(). michael@0: while (subtle::Acquire_Load(state) == kLazyInstanceStateCreating) { michael@0: PlatformThread::YieldCurrentThread(); michael@0: } michael@0: // Someone else created the instance. michael@0: return false; michael@0: } michael@0: michael@0: void CompleteLazyInstance(subtle::AtomicWord* state, michael@0: subtle::AtomicWord new_instance, michael@0: void* lazy_instance, michael@0: void (*dtor)(void*)) { michael@0: // See the comment to the corresponding HAPPENS_AFTER in Pointer(). michael@0: ANNOTATE_HAPPENS_BEFORE(state); michael@0: michael@0: // Instance is created, go from CREATING to CREATED. michael@0: // Releases visibility over private_buf_ to readers. Pairing Acquire_Load's michael@0: // are in NeedsInstance() and Pointer(). michael@0: subtle::Release_Store(state, new_instance); michael@0: michael@0: // Make sure that the lazily instantiated object will get destroyed at exit. michael@0: if (dtor) michael@0: AtExitManager::RegisterCallback(dtor, lazy_instance); michael@0: } michael@0: michael@0: } // namespace internal michael@0: } // namespace base