michael@0: // Copyright (c) 2008 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/platform_thread.h" michael@0: michael@0: namespace base { michael@0: michael@0: void LazyInstanceHelper::EnsureInstance(void* instance, michael@0: void (*ctor)(void*), michael@0: void (*dtor)(void*)) { michael@0: // Try to create the instance, if we're the first, will go from EMPTY michael@0: // to CREATING, otherwise we've already been beaten here. michael@0: if (base::subtle::Acquire_CompareAndSwap( michael@0: &state_, STATE_EMPTY, STATE_CREATING) == STATE_EMPTY) { michael@0: // Created the instance in the space provided by |instance|. michael@0: ctor(instance); michael@0: // Instance is created, go from CREATING to CREATED. michael@0: base::subtle::Release_Store(&state_, STATE_CREATED); michael@0: // Register the destructor callback with AtExitManager. michael@0: base::AtExitManager::RegisterCallback(dtor, instance); michael@0: } else { michael@0: // It's either in the process of being created, or already created. Spin. michael@0: while (base::subtle::NoBarrier_Load(&state_) != STATE_CREATED) michael@0: PlatformThread::YieldCurrentThread(); michael@0: } michael@0: } michael@0: michael@0: } // namespace base