/src/mozilla-central/security/sandbox/chromium/base/lazy_instance.cc
Line | Count | Source (jump to first uncovered line) |
1 | | // Copyright (c) 2011 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/threading/platform_thread.h" |
10 | | |
11 | | namespace base { |
12 | | namespace internal { |
13 | | |
14 | | // TODO(joth): This function could be shared with Singleton, in place of its |
15 | | // WaitForInstance() call. |
16 | 0 | bool NeedsLazyInstance(subtle::AtomicWord* state) { |
17 | 0 | // Try to create the instance, if we're the first, will go from 0 to |
18 | 0 | // kLazyInstanceStateCreating, otherwise we've already been beaten here. |
19 | 0 | // The memory access has no memory ordering as state 0 and |
20 | 0 | // kLazyInstanceStateCreating have no associated data (memory barriers are |
21 | 0 | // all about ordering of memory accesses to *associated* data). |
22 | 0 | if (subtle::NoBarrier_CompareAndSwap(state, 0, |
23 | 0 | kLazyInstanceStateCreating) == 0) |
24 | 0 | // Caller must create instance |
25 | 0 | return true; |
26 | 0 | |
27 | 0 | // It's either in the process of being created, or already created. Spin. |
28 | 0 | // The load has acquire memory ordering as a thread which sees |
29 | 0 | // state_ == STATE_CREATED needs to acquire visibility over |
30 | 0 | // the associated data (buf_). Pairing Release_Store is in |
31 | 0 | // CompleteLazyInstance(). |
32 | 0 | while (subtle::Acquire_Load(state) == kLazyInstanceStateCreating) { |
33 | 0 | PlatformThread::YieldCurrentThread(); |
34 | 0 | } |
35 | 0 | // Someone else created the instance. |
36 | 0 | return false; |
37 | 0 | } |
38 | | |
39 | | void CompleteLazyInstance(subtle::AtomicWord* state, |
40 | | subtle::AtomicWord new_instance, |
41 | | void (*destructor)(void*), |
42 | 0 | void* destructor_arg) { |
43 | 0 | // Instance is created, go from CREATING to CREATED. |
44 | 0 | // Releases visibility over private_buf_ to readers. Pairing Acquire_Load's |
45 | 0 | // are in NeedsInstance() and Pointer(). |
46 | 0 | subtle::Release_Store(state, new_instance); |
47 | 0 |
|
48 | 0 | // Make sure that the lazily instantiated object will get destroyed at exit. |
49 | 0 | if (destructor) |
50 | 0 | AtExitManager::RegisterCallback(destructor, destructor_arg); |
51 | 0 | } |
52 | | |
53 | | } // namespace internal |
54 | | } // namespace base |