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