• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright (c) 2010 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include "base/lazy_instance.h"
6 
7 #include "base/at_exit.h"
8 #include "base/atomicops.h"
9 #include "base/basictypes.h"
10 #include "base/threading/platform_thread.h"
11 #include "base/third_party/dynamic_annotations/dynamic_annotations.h"
12 
13 namespace base {
14 
NeedsInstance()15 bool LazyInstanceHelper::NeedsInstance() {
16   // Try to create the instance, if we're the first, will go from EMPTY
17   // to CREATING, otherwise we've already been beaten here.
18   if (base::subtle::Acquire_CompareAndSwap(
19           &state_, STATE_EMPTY, STATE_CREATING) == STATE_EMPTY) {
20     // Caller must create instance
21     return true;
22   } else {
23     // It's either in the process of being created, or already created.  Spin.
24     while (base::subtle::NoBarrier_Load(&state_) != STATE_CREATED)
25       PlatformThread::YieldCurrentThread();
26   }
27 
28   // Someone else created the instance.
29   return false;
30 }
31 
CompleteInstance(void * instance,void (* dtor)(void *))32 void LazyInstanceHelper::CompleteInstance(void* instance, void (*dtor)(void*)) {
33   // See the comment to the corresponding HAPPENS_AFTER in Pointer().
34   ANNOTATE_HAPPENS_BEFORE(&state_);
35 
36   // Instance is created, go from CREATING to CREATED.
37   base::subtle::Release_Store(&state_, STATE_CREATED);
38 
39   // Make sure that the lazily instantiated object will get destroyed at exit.
40   if (dtor)
41     base::AtExitManager::RegisterCallback(dtor, instance);
42 }
43 
44 }  // namespace base
45