1 // Copyright 2018 The Chromium Authors
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_helpers.h"
6
7 #include <atomic>
8
9 #include "base/at_exit.h"
10 #include "base/threading/platform_thread.h"
11
12 namespace base {
13 namespace internal {
14
NeedsLazyInstance(std::atomic<uintptr_t> & state)15 bool NeedsLazyInstance(std::atomic<uintptr_t>& state) {
16 // Try to create the instance, if we're the first, will go from 0 to
17 // kLazyInstanceStateCreating, otherwise we've already been beaten here.
18 // The memory access has no memory ordering as state 0 and
19 // kLazyInstanceStateCreating have no associated data (memory barriers are
20 // all about ordering of memory accesses to *associated* data).
21 uintptr_t expected = 0;
22 if (state.compare_exchange_strong(expected, kLazyInstanceStateCreating,
23 std::memory_order_relaxed,
24 std::memory_order_relaxed)) {
25 // Caller must create instance
26 return true;
27 }
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 if (state.load(std::memory_order_acquire) == kLazyInstanceStateCreating) {
35 const base::TimeTicks start = base::TimeTicks::Now();
36 do {
37 const base::TimeDelta elapsed = base::TimeTicks::Now() - start;
38 // Spin with YieldCurrentThread for at most one ms - this ensures
39 // maximum responsiveness. After that spin with Sleep(1ms) so that we
40 // don't burn excessive CPU time - this also avoids infinite loops due
41 // to priority inversions (https://crbug.com/797129).
42 if (elapsed < Milliseconds(1))
43 PlatformThread::YieldCurrentThread();
44 else
45 PlatformThread::Sleep(Milliseconds(1));
46 } while (state.load(std::memory_order_acquire) ==
47 kLazyInstanceStateCreating);
48 }
49 // Someone else created the instance.
50 return false;
51 }
52
CompleteLazyInstance(std::atomic<uintptr_t> & state,uintptr_t new_instance,void (* destructor)(void *),void * destructor_arg)53 void CompleteLazyInstance(std::atomic<uintptr_t>& state,
54 uintptr_t new_instance,
55 void (*destructor)(void*),
56 void* destructor_arg) {
57 // Instance is created, go from CREATING to CREATED (or reset it if
58 // |new_instance| is null). Releases visibility over |private_buf_| to
59 // readers. Pairing Acquire_Load is in NeedsLazyInstance().
60 state.store(new_instance, std::memory_order_release);
61
62 // Make sure that the lazily instantiated object will get destroyed at exit.
63 if (new_instance && destructor)
64 AtExitManager::RegisterCallback(destructor, destructor_arg);
65 }
66
67 } // namespace internal
68 } // namespace base
69