Coverage Report

Created: 2026-09-14 06:45

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/abseil-cpp/absl/base/internal/thread_identity.h
Line
Count
Source
1
// Copyright 2017 The Abseil Authors.
2
//
3
// Licensed under the Apache License, Version 2.0 (the "License");
4
// you may not use this file except in compliance with the License.
5
// You may obtain a copy of the License at
6
//
7
//      https://www.apache.org/licenses/LICENSE-2.0
8
//
9
// Unless required by applicable law or agreed to in writing, software
10
// distributed under the License is distributed on an "AS IS" BASIS,
11
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
// See the License for the specific language governing permissions and
13
// limitations under the License.
14
//
15
// Each active thread has an ThreadIdentity that may represent the thread in
16
// various level interfaces.  ThreadIdentity objects are never deallocated.
17
// When a thread terminates, its ThreadIdentity object may be reused for a
18
// thread created later.
19
20
#ifndef ABSL_BASE_INTERNAL_THREAD_IDENTITY_H_
21
#define ABSL_BASE_INTERNAL_THREAD_IDENTITY_H_
22
23
#include <atomic>
24
#include <cstddef>
25
#include <cstdint>
26
27
#include "absl/base/attributes.h"
28
#include "absl/base/config.h"
29
#include "absl/base/internal/per_thread_tls.h"
30
#include "absl/base/optimization.h"
31
32
#ifndef _WIN32
33
#include <pthread.h>
34
// Defines __GOOGLE_GRTE_VERSION__ (via glibc-specific features.h) when
35
// supported.
36
#include <unistd.h>
37
#endif
38
39
namespace absl {
40
ABSL_NAMESPACE_BEGIN
41
42
struct SynchLocksHeld;
43
struct SynchWaitParams;
44
45
namespace base_internal {
46
47
class SpinLock;
48
struct ThreadIdentity;
49
50
// Used by the implementation of absl::Mutex and absl::CondVar.
51
struct PerThreadSynch {
52
  // The internal representation of absl::Mutex and absl::CondVar rely
53
  // on the alignment of PerThreadSynch. Both store the address of the
54
  // PerThreadSynch in the high-order bits of their internal state,
55
  // which means the low kLowZeroBits of the address of PerThreadSynch
56
  // must be zero.
57
  static constexpr int kLowZeroBits = 8;
58
  static constexpr int kAlignment = 1 << kLowZeroBits;
59
60
  // Returns the associated ThreadIdentity.
61
  // This can be implemented as a cast because we guarantee
62
  // PerThreadSynch is the first element of ThreadIdentity.
63
0
  ThreadIdentity* thread_identity() {
64
0
    return reinterpret_cast<ThreadIdentity*>(this);
65
0
  }
66
67
  PerThreadSynch* next;  // Circular waiter queue; initialized to 0.
68
  PerThreadSynch* skip;  // If non-zero, all entries in Mutex queue
69
                         // up to and including "skip" have same
70
                         // condition as this, and will be woken later
71
  bool may_skip;         // if false while on mutex queue, a mutex unlocker
72
                         // is using this PerThreadSynch as a terminator.  Its
73
                         // skip field must not be filled in because the loop
74
                         // might then skip over the terminator.
75
  bool wake;             // This thread is to be woken from a Mutex.
76
  // If "x" is on a waiter list for a mutex, "x->cond_waiter" is true iff the
77
  // waiter is waiting on the mutex as part of a CV Wait or Mutex Await.
78
  //
79
  // The value of "x->cond_waiter" is meaningless if "x" is not on a
80
  // Mutex waiter list.
81
  bool cond_waiter;
82
  bool maybe_unlocking;  // Valid at head of Mutex waiter queue;
83
                         // true if UnlockSlow could be searching
84
                         // for a waiter to wake.  Used for an optimization
85
                         // in Enqueue().  true is always a valid value.
86
                         // Can be reset to false when the unlocker or any
87
                         // writer releases the lock, or a reader fully
88
                         // releases the lock.  It may not be set to false
89
                         // by a reader that decrements the count to
90
                         // non-zero. protected by mutex spinlock
91
  bool suppress_fatal_errors;  // If true, try to proceed even in the face
92
                               // of broken invariants.  This is used within
93
                               // fatal signal handlers to improve the
94
                               // chances of debug logging information being
95
                               // output successfully.
96
  int priority;                // Priority of thread (updated every so often).
97
98
  // State values:
99
  //   kAvailable: This PerThreadSynch is available.
100
  //   kQueued: This PerThreadSynch is unavailable, it's currently queued on a
101
  //            Mutex or CondVar waistlist.
102
  //
103
  // Transitions from kQueued to kAvailable require a release
104
  // barrier. This is needed as a waiter may use "state" to
105
  // independently observe that it's no longer queued.
106
  //
107
  // Transitions from kAvailable to kQueued require no barrier, they
108
  // are externally ordered by the Mutex.
109
  enum State { kAvailable, kQueued };
110
  std::atomic<State> state;
111
112
  // The wait parameters of the current wait.  waitp is null if the
113
  // thread is not waiting. Transitions from null to non-null must
114
  // occur before the enqueue commit point (state = kQueued in
115
  // Enqueue() and CondVarEnqueue()). Transitions from non-null to
116
  // null must occur after the wait is finished (state = kAvailable in
117
  // Mutex::Block() and CondVar::WaitCommon()). This field may be
118
  // changed only by the thread that describes this PerThreadSynch.  A
119
  // special case is Fer(), which calls Enqueue() on another thread,
120
  // but with an identical SynchWaitParams pointer, thus leaving the
121
  // pointer unchanged.
122
  SynchWaitParams* waitp;
123
124
  intptr_t readers;  // Number of readers in mutex.
125
126
  // When priority will next be read (cycles).
127
  int64_t next_priority_read_cycles;
128
129
  // Locks held; used during deadlock detection.
130
  // Allocated in Synch_GetAllLocks() and freed in ReclaimThreadIdentity().
131
  SynchLocksHeld* all_locks;
132
};
133
134
// The instances of this class are allocated in NewThreadIdentity() with an
135
// alignment of PerThreadSynch::kAlignment and never destroyed. Initialization
136
// should happen in OneTimeInitThreadIdentity().
137
//
138
// Instances may be reused by new threads - fields should be reset in
139
// ResetThreadIdentityBetweenReuse().
140
//
141
// NOTE: The layout of fields in this structure is critical, please do not
142
//       add, remove, or modify the field placements without fully auditing the
143
//       layout.
144
struct ThreadIdentity {
145
  // Must be the first member.  The Mutex implementation requires that
146
  // the PerThreadSynch object associated with each thread is
147
  // PerThreadSynch::kAlignment aligned.  We provide this alignment on
148
  // ThreadIdentity itself.
149
  PerThreadSynch per_thread_synch;
150
151
  struct SchedulerState {
152
    std::atomic<void*> bound_schedulable{nullptr};
153
    // Storage space for a SpinLock, which is created through a placement new to
154
    // break a dependency cycle.
155
    uint32_t association_lock_word;
156
    std::atomic<int> scheduling_disabled_depth;
157
    int potentially_blocking_depth;
158
    uint32_t schedule_next_state;
159
160
    // When true, current thread is unlocking a mutex and actively waking a
161
    // thread that was previously waiting, but that lock has yet more waiters.
162
    // Used to signal to schedulers that work being woken should get an
163
    // elevated priority.
164
    bool waking_designated_waker;
165
166
0
    inline SpinLock* association_lock() {
167
0
      return reinterpret_cast<SpinLock*>(&association_lock_word);
168
0
    }
169
  } scheduler_state;  // Private: Reserved for use in Gloop
170
171
  // For worker threads that may not be doing any interesting user work, this
172
  // tracks the current state of the worker. This is used to handle those
173
  // threads differently e.g. when printing stacktraces.
174
  //
175
  // It should only be written to by the thread itself.
176
  //
177
  // Note that this is different from the mutex idle bit - threads running user
178
  // work can be waiting but still be active.
179
  //
180
  // Note: not all parts of the code-base may maintain this field correctly and
181
  // therefore this field should only be used to improve debugging/monitoring.
182
  //
183
  // Put it here to reuse some of the padding space.
184
  enum class WaitState : uint8_t {
185
    kActive = 0,
186
    kWaitingForWork = 1,
187
  };
188
  std::atomic<WaitState> wait_state;
189
  static_assert(std::atomic<WaitState>::is_always_lock_free);
190
191
  // Add a padding such that scheduler_state is on a different cache line than
192
  // waiter state.  We use padding here, so that the size of the structure does
193
  // not substantially grow due to the added padding.
194
  static constexpr size_t kToBePaddedSize =
195
      sizeof(SchedulerState) + sizeof(std::atomic<WaitState>);
196
  static_assert(ABSL_CACHELINE_SIZE >= kToBePaddedSize);
197
  char padding[ABSL_CACHELINE_SIZE - kToBePaddedSize];
198
199
  // Private: Reserved for absl::synchronization_internal::Waiter.
200
  struct WaiterState {
201
    alignas(void*) char data[256];
202
  } waiter_state;
203
204
  // Used by PerThreadSem::{Get,Set}ThreadBlockedCounter().
205
  std::atomic<int>* blocked_count_ptr;
206
207
  // The following variables are mostly read/written just by the
208
  // thread itself.  The only exception is that these are read by
209
  // a ticker thread as a hint.
210
  std::atomic<int> ticker;      // Tick counter, incremented once per second.
211
  std::atomic<int> wait_start;  // Ticker value when thread started waiting.
212
  std::atomic<bool> is_idle;    // Has thread become idle yet?
213
214
  // For tracking depth of __cxa_guard_acquire.  This used to recognize heap
215
  // allocations for function static objects.
216
  int static_initialization_depth;
217
218
  ThreadIdentity* next;
219
};
220
221
// Returns the ThreadIdentity object representing the calling thread; guaranteed
222
// to be unique for its lifetime.  The returned object will remain valid for the
223
// program's lifetime; although it may be re-assigned to a subsequent thread.
224
// If one does not exist, return nullptr instead.
225
//
226
// Does not malloc(*), and is async-signal safe.
227
// [*] Technically pthread_setspecific() does malloc on first use; however this
228
// is handled internally within tcmalloc's initialization already. Note that
229
// darwin does *not* use tcmalloc, so this can catch you if using MallocHooks
230
// on Apple platforms. Whatever function is calling your MallocHooks will need
231
// to watch for recursion on Apple platforms.
232
//
233
// New ThreadIdentity objects can be constructed and associated with a thread
234
// by calling GetOrCreateCurrentThreadIdentity() in per-thread-sem.h.
235
ThreadIdentity* CurrentThreadIdentityIfPresent();
236
237
using ThreadIdentityReclaimerFunction = void (*)(void*);
238
239
// Sets the current thread identity to the given value.  'reclaimer' is a
240
// pointer to the global function for cleaning up instances on thread
241
// destruction.
242
void SetCurrentThreadIdentity(ThreadIdentity* identity,
243
                              ThreadIdentityReclaimerFunction reclaimer);
244
245
// Removes the currently associated ThreadIdentity from the running thread.
246
// This must be called from inside the ThreadIdentityReclaimerFunction, and only
247
// from that function.
248
void ClearCurrentThreadIdentity();
249
250
// May be chosen at compile time via: -DABSL_FORCE_THREAD_IDENTITY_MODE=<mode
251
// index>
252
#ifdef ABSL_THREAD_IDENTITY_MODE_USE_POSIX_SETSPECIFIC
253
#error ABSL_THREAD_IDENTITY_MODE_USE_POSIX_SETSPECIFIC cannot be directly set
254
#else
255
#define ABSL_THREAD_IDENTITY_MODE_USE_POSIX_SETSPECIFIC 0
256
#endif
257
258
#ifdef ABSL_THREAD_IDENTITY_MODE_USE_TLS
259
#error ABSL_THREAD_IDENTITY_MODE_USE_TLS cannot be directly set
260
#else
261
#define ABSL_THREAD_IDENTITY_MODE_USE_TLS 1
262
#endif
263
264
#ifdef ABSL_THREAD_IDENTITY_MODE_USE_CPP11
265
#error ABSL_THREAD_IDENTITY_MODE_USE_CPP11 cannot be directly set
266
#else
267
#define ABSL_THREAD_IDENTITY_MODE_USE_CPP11 2
268
#endif
269
270
#ifdef ABSL_THREAD_IDENTITY_MODE
271
#error ABSL_THREAD_IDENTITY_MODE cannot be directly set
272
#elif defined(ABSL_FORCE_THREAD_IDENTITY_MODE)
273
#define ABSL_THREAD_IDENTITY_MODE ABSL_FORCE_THREAD_IDENTITY_MODE
274
#elif defined(_WIN32) && !defined(__MINGW32__)
275
#define ABSL_THREAD_IDENTITY_MODE ABSL_THREAD_IDENTITY_MODE_USE_CPP11
276
#elif defined(__APPLE__) && defined(ABSL_HAVE_THREAD_LOCAL)
277
#define ABSL_THREAD_IDENTITY_MODE ABSL_THREAD_IDENTITY_MODE_USE_CPP11
278
#elif ABSL_PER_THREAD_TLS && defined(__GOOGLE_GRTE_VERSION__) && \
279
    (__GOOGLE_GRTE_VERSION__ >= 20140228L)
280
// Support for async-safe TLS was specifically added in GRTEv4.  It's not
281
// present in the upstream eglibc.
282
// Note:  Current default for production systems.
283
#define ABSL_THREAD_IDENTITY_MODE ABSL_THREAD_IDENTITY_MODE_USE_TLS
284
#else
285
#define ABSL_THREAD_IDENTITY_MODE \
286
  ABSL_THREAD_IDENTITY_MODE_USE_POSIX_SETSPECIFIC
287
#endif
288
289
#if ABSL_THREAD_IDENTITY_MODE == ABSL_THREAD_IDENTITY_MODE_USE_TLS || \
290
    ABSL_THREAD_IDENTITY_MODE == ABSL_THREAD_IDENTITY_MODE_USE_CPP11
291
292
#if ABSL_PER_THREAD_TLS
293
ABSL_CONST_INIT extern ABSL_PER_THREAD_TLS_KEYWORD ThreadIdentity*
294
    thread_identity_ptr;
295
#elif defined(ABSL_HAVE_THREAD_LOCAL)
296
ABSL_CONST_INIT extern thread_local ThreadIdentity* thread_identity_ptr;
297
#else
298
#error Thread-local storage not detected on this platform
299
#endif
300
301
// thread_local variables cannot be in headers exposed by DLLs or in certain
302
// build configurations on Apple platforms. However, it is important for
303
// performance reasons in general that `CurrentThreadIdentityIfPresent` be
304
// inlined. In the other cases we opt to have the function not be inlined. Note
305
// that `CurrentThreadIdentityIfPresent` is declared above so we can exclude
306
// this entire inline definition.
307
#if !defined(__APPLE__) && !defined(ABSL_BUILD_DLL) && \
308
    !defined(ABSL_CONSUME_DLL)
309
#define ABSL_INTERNAL_INLINE_CURRENT_THREAD_IDENTITY_IF_PRESENT 1
310
#endif
311
312
#ifdef ABSL_INTERNAL_INLINE_CURRENT_THREAD_IDENTITY_IF_PRESENT
313
inline ThreadIdentity* CurrentThreadIdentityIfPresent() {
314
  return thread_identity_ptr;
315
}
316
#endif
317
318
#elif ABSL_THREAD_IDENTITY_MODE != \
319
    ABSL_THREAD_IDENTITY_MODE_USE_POSIX_SETSPECIFIC
320
#error Unknown ABSL_THREAD_IDENTITY_MODE
321
#endif
322
323
}  // namespace base_internal
324
ABSL_NAMESPACE_END
325
}  // namespace absl
326
327
#endif  // ABSL_BASE_INTERNAL_THREAD_IDENTITY_H_