Stroika Library 3.0d25
 
Loading...
Searching...
No Matches
AssertExternallySynchronizedChecker.h
Go to the documentation of this file.
1/*
2 * Copyright(c) Sophist Solutions, Inc. 1990-2026. All rights reserved
3 */
4#ifndef _Stroika_Foundation_Debug_AssertExternallySynchronizedChecker_h_
5#define _Stroika_Foundation_Debug_AssertExternallySynchronizedChecker_h_ 1
6
7#include "Stroika/Foundation/StroikaPreComp.h"
8
9#include <algorithm>
10#include <array>
11#include <atomic>
12#include <forward_list>
13#include <memory>
14#include <mutex>
15#include <optional>
16#include <shared_mutex>
17#include <thread>
18
19#include "Stroika/Foundation/Common/Common.h"
20#include "Stroika/Foundation/Common/Concepts.h"
24
25/**
26 * \file
27 *
28 * \note Code-Status: <a href="Code-Status.md#Release">Release</a>
29 *
30 * TODO:
31 * @todo see if fSharedLocks_ can be replaced with LOCK-FREE - at least 99% of the time.... Locks affect timing, and can hide thread
32 * bugs. Quickie attempt at profiling yields that that time is NOT spent with the locks but with the remove()
33 * code (since I switched from multiset to forward_list, so maybe cuz of that). Or could be bad measurement (I just
34 * test on DEBUG builds).
35 *
36 * Since Stroika 2.1b10 we do have a lock/free forward_list class I could try. But I'm not yet confident
37 * in its stability, so maybe sometime down the road...
38 *
39 * @see https://github.com/SophistSolutions/Stroika/issues/676 (STK-540) for details on stuff todo above
40 *
41 * @todo Reconsider if AssertExternallySynchronizedChecker::operator= should allow for this to be locked
42 * by the current thread. Safe to do later as that would be weakening the current check/requirement.
43 */
44
45namespace Stroika::Foundation::Debug {
46
47 /**
48 * \brief qStroika_Foundation_Debug_AssertExternallySynchronizedChecker_Enabled controls if this threaded access protection
49 *
50 * The compilation compile-time macro qStroika_Foundation_Debug_AssertExternallySynchronizedChecker_Enabled can be used
51 * to control if AssertExternallySynchronizedChecker checking is enabled.
52 *
53 * If its not defined (typical), we look at qStroika_Foundation_Debug_AssertionsChecked. If that is false, qStroika_Foundation_Debug_AssertExternallySynchronizedChecker_Enabled is disabled.
54 *
55 * If qStroika_Foundation_Debug_AssertionsChecked is true, BUT, we have TSAN enabled, we STILL (change in Stroika v3.0d1) - DISABLE kAssertExternallySynchronizedCheckerEnabled
56 * since its slow, and redundant.
57 *
58 * Only if qStroika_Foundation_Debug_AssertionsChecked is true, there is no TSAN, and qStroika_Foundation_Debug_AssertExternallySynchronizedChecker_Enabled is made
59 * do we turn on qStroika_Foundation_Debug_AssertExternallySynchronizedChecker_Enabled.
60 *
61 * \note TRIED to do this with constexpr bool kAssertExternallySynchronizedCheckerEnabled, but as of C++20 rules
62 * still too much of a PITA to use: cannot conditionally define classes, and nearly anything
63 * based on requires/if constexpr, unless it is a template.
64 */
65// DEPRECATED spelling (before Stroika v3.0d24 this class was called AssertExternallySynchronizedMutex).
66// Honored so that an existing build defining the old macro keeps the setting it asked for, rather than
67// silently falling through to the default below. Remove when the deprecated header goes.
68#if defined(qStroika_Foundation_Debug_AssertExternallySynchronizedMutex_Enabled) and \
69 not defined(qStroika_Foundation_Debug_AssertExternallySynchronizedChecker_Enabled)
70#define qStroika_Foundation_Debug_AssertExternallySynchronizedChecker_Enabled \
71 qStroika_Foundation_Debug_AssertExternallySynchronizedMutex_Enabled
72#endif
73
74#if not defined(qStroika_Foundation_Debug_AssertExternallySynchronizedChecker_Enabled)
75// off when built with the thread sanitizer - this is the compile-time test documented at Debug::kBuiltWithThreadSanitizer
76#if defined(__SANITIZE_THREAD__)
77#define qStroika_Foundation_Debug_AssertExternallySynchronizedChecker_Enabled 0
78#elif defined(__has_feature)
79#if __has_feature(thread_sanitizer)
80#define qStroika_Foundation_Debug_AssertExternallySynchronizedChecker_Enabled 0
81#endif
82#endif
83#endif
84#if not defined(qStroika_Foundation_Debug_AssertExternallySynchronizedChecker_Enabled)
85#if qStroika_Foundation_Debug_AssertionsChecked
86#define qStroika_Foundation_Debug_AssertExternallySynchronizedChecker_Enabled 1
87#else
88#define qStroika_Foundation_Debug_AssertExternallySynchronizedChecker_Enabled 0
89#endif
90#endif
91
92 /**
93 * \brief NOT a real mutex - just a debugging infrastructure support tool so in debug builds can be assured threadsafe, which is syntactically used like a mutex, for SIMILAR reasons in similar places
94 *
95 * This class is a 'no op' in production builds (so zero cost in release builds, assumes caller ensures thread safety).
96 *
97 * AssertExternallySynchronizedChecker follows the pattern of (a recursive-mutex) - or really super-recursive - because it allows
98 * lock/shared_lock to be mixed logically (unlike stdc++ shared_mutex).
99 *
100 * \note This means it is LEGAL to call lock () while holding a shared_lock, IFF that shared_lock is for the
101 * same thread. It is implicitly an 'UpgradeLock'
102 *
103 * Externally synchronized means that some external application control guarantees the section of code (or data)
104 * is only accessed by a single thread.
105 *
106 * This can be used to guarantee the same level of thread safety as provided in the std c++ libraries:
107 * Allow multiple readers (shared locks) from multiple threads, but if any thread has
108 * a lock (writer), then no other threads my read or write lock (in any order).
109 *
110 * In debug builds, it enforces this fact through assertions.
111 *
112 * \note This doesn't guarantee catching all races (with no happens-before), but it catches many incorrect thread usage cases
113 *
114 * \note ***Not Cancelation Point***
115 *
116 * \note methods all noexcept (just asserts out on problems) - noexcept so debug semantics same as release semantics
117 * Since the DEBUG version will allocate memory, which may fail, those failures trigger assertion failure and abort.
118 *
119 * \note typically used as
120 * Stroika_ATTRIBUTE_NO_UNIQUE_ADDRESS Debug::AssertExternallySynchronizedChecker fThisAssertExternallySynchronized_;
121 *
122 * \note Satisfies Concepts:
123 * o movable<AssertExternallySynchronizedChecker>
124 * o copyable<AssertExternallySynchronizedChecker>
125 * o Common::StdCompat::Lockable<AssertExternallySynchronizedChecker>
126 *
127 * \note movable/copyable is REQUIRED, and is where this most visibly parts company with a real mutex
128 * (std::mutex is neither). Objects embed one of these to be checked, and Stroika objects are
129 * copy-by-value, so the checker has to copy and move along with its owner. See the static_assert
130 * at the bottom of this file for the full rationale.
131 *
132 * \par Example Usage
133 * \code
134 * struct foo {
135 * Stroika_ATTRIBUTE_NO_UNIQUE_ADDRESS Debug::AssertExternallySynchronizedChecker fThisAssertExternallySynchronized_;
136 * inline void DoReadWriteStuffOnData ()
137 * {
138 * AssertExternallySynchronizedChecker::WriteContext declareContext { fThisAssertExternallySynchronized_ };
139 * // now do what you usually do for to modify locked data...
140 * }
141 * inline void DoReadOnlyStuffOnData ()
142 * {
143 * AssertExternallySynchronizedChecker::ReadContext declareContext { fThisAssertExternallySynchronized_ };
144 * // now do what you usually do for DoReadOnlyStuffOnData - reading data only...
145 * }
146 * };
147 * \endcode
148 *
149 * \par Example Usage
150 * \code
151 * // this style of use - subclassing - is especially useful if the object foo will be subclassed, and checked throughout the
152 * // code (or subclasses) with Debug::AssertExternallySynchronizedChecker::ReadContext (or WriteContext)
153 * struct foo : public Debug::AssertExternallySynchronizedChecker {
154 * inline void DoReadWriteStuffOnData ()
155 * {
156 * AssertExternallySynchronizedChecker::WriteContext declareContext { *this }; // lock_guard or scopedLock or unique_lock
157 * // now do what you usually do for to modify locked data...
158 * }
159 * inline void DoReadOnlyStuffOnData ()
160 * {
161 * AssertExternallySynchronizedChecker::ReadContext declareContext { *this };
162 * // now do what you usually do for DoReadOnlyStuffOnData - reading data only...
163 * }
164 * };
165 * \endcode
166 *
167 * \note This is SUPER-RECURSIVE lock. It allows lock() when shared_lock held (by only this thread) - so upgrades the lock.
168 * And it allows shared_lock when lock held by the same thread. Otherwise it asserts when a thread conflict is found.
169 * lock() and shared_lock () - here - are NEVER blocking. They just assert there is no conflict.
170 */
172#if qStroika_Foundation_Debug_AssertExternallySynchronizedChecker_Enabled
173 public:
174 /**
175 * Explicit shared context object, so we can construct multiple AssertExternallySynchronizedChecker which all
176 * share a common 'sharedContext' - representing that they ALL must be externally synchronized across all the cooperating objects
177 *
178 * In most cases, just ignore this class.
179 *
180 * To have N cooperating classes (e.g. object, and a few direct members) all share the same rules of single-threading (treating them all
181 * as one object for the purpose of the rules of safe multithread access) - arrange for them to share a common 'sharedContext'
182 *
183 * \note class marked final to make more clear why safe to not have virtual destructor
184 */
185 struct SharedContext final {
186 public:
187 SharedContext () noexcept = default;
188 SharedContext (const SharedContext&) = delete;
189 SharedContext& operator= (const SharedContext&) = delete;
190 ~SharedContext ();
191
192 private:
193 atomic_uint_fast32_t fFullLocks_{0};
194 thread::id fThreadWithFullLock_; // or value undefined/last value where it had full lock
195
196 private:
197 // Use of inline array avoids mallocs, and makes this run slightly faster. No semantic differerence,
198 // just makes debug mode a bit faster.
199 static constexpr size_t kInlineSharedLockBufSize_ = 2;
200 struct {
201 // most logically a multiset, but std::multiset is not threadsafe and requires external locking.
202 // So does forward_list, but its closer to lock free, so try it for now
203 // GetSharedLockMutexThreads_ () used to access fSharedLocks_
204 array<thread::id, kInlineSharedLockBufSize_> fInitialThreads_;
205 uint8_t fInitialThreadsSize_{0}; // not sure how to add this field only conditionally
206 forward_list<thread::id> fOverflowThreads_;
207 } fSharedLocks_;
208
209 private:
210 bool GetSharedLockEmpty_ () const;
211 pair<size_t, size_t> CountSharedLockThreads_ () const;
212 size_t GetSharedLockThreadsCount_ () const;
213 size_t CountOfIInSharedLockThreads_ (thread::id i) const;
214 void AddSharedLock_ (thread::id i);
215 void RemoveSharedLock_ (thread::id i);
216
217 private:
219 };
220#endif
221
222 public:
223 /**
224 * \note Copy/Move constructor checks for existing locks while copying.
225 * Must be able to read lock source on copy, and have zero existing locks on src for move.
226 * These 'constructors' don't really do/copy/move anything, but just check the state of their own
227 * lock count and the state of the 'src' lock counts.
228 *
229 * NOTE - the 'SharedContext' does NOT get copied by copy constructors, move constructors etc. Its tied
230 * to the l-value.
231 */
232#if qStroika_Foundation_Debug_AssertExternallySynchronizedChecker_Enabled
233 AssertExternallySynchronizedChecker (const shared_ptr<SharedContext>& sharedContext = nullptr) noexcept;
234 AssertExternallySynchronizedChecker (const shared_ptr<SharedContext>& sharedContext, AssertExternallySynchronizedChecker&& src) noexcept;
237 AssertExternallySynchronizedChecker (const shared_ptr<SharedContext>& sharedContext, const AssertExternallySynchronizedChecker& src) noexcept;
238#else
239 constexpr AssertExternallySynchronizedChecker () noexcept = default;
242#endif
243
244 public:
245 /**
246 * \note operator= checks for existing locks while copying.
247 * Must be able to read lock source on copy, and have zero existing locks on target or move.
248 */
251
252#if qStroika_Foundation_Debug_AssertExternallySynchronizedChecker_Enabled
253 public:
254 nonvirtual shared_ptr<SharedContext> GetSharedContext () const;
255
256 public:
257 /**
258 * Make it easy for subclasses to expose SetAssertExternallySynchronizedCheckerContext () functionality, so those
259 * subclasses can allow users of those classes to share a sharing context.
260 *
261 * \note - this is named without the prefixing '_' (though protected) to make it easier to forward, just using using.
262 */
263 nonvirtual void SetAssertExternallySynchronizedCheckerContext (const shared_ptr<SharedContext>& sharedContext);
264#endif
265
266 public:
267 /**
268 * Saves current thread, and increments lock count, and
269 * \pre already locked by this thread or no existing locks (either shared or exclusive)
270 *
271 * \note method non-const (can always const_cast if needed) because of standard C++ convention of non-const objects
272 * for write-lock
273 */
274 nonvirtual void lock () noexcept;
275
276 public:
277 /**
278 * \brief Like lock() - if it would succeed, same then, but if would fail instead of assert out, just return false.
279 */
280 nonvirtual bool try_lock () noexcept;
281
282 public:
283 /**
284 * Just decrement lock count
285 *
286 * \pre still running on the same locking thread and locks not unbalanced
287 */
288 nonvirtual void unlock () noexcept;
289
290 public:
291 /**
292 * Saves current thread (multiset), and increments shared count, and
293 * \pre no pre-existing locks on other threads
294 *
295 * \note method const despite usual lockable rules, so easier to work with 'const' objects being 'marked' as doing a read operation.
296 */
297 nonvirtual void lock_shared () const noexcept;
298
299 public:
300 /**
301 * Just decrement shared lock count (remove this thread from shared lock multiset)
302 *
303 * \note see lock_shard for why const.
304 *
305 * \pre still running on the same locking thread and locks not unbalanced
306 */
307 nonvirtual void unlock_shared () const noexcept;
308
309 public:
310 /**
311 * \brief Instantiate AssertExternallySynchronizedChecker::ReadContext to designate an area of code where protected data will be read
312 *
313 * This type alias makes a little more clear in reading code that the 'lock' is really just an assertion about thread safety
314 *
315 * Since AssertExternallySynchronizedChecker follows the concept 'mutex' you can obviously use any
316 * of the standard lockers in std::c++, but using AssertExternallySynchronizedChecker::ReadContext - makes it a little more clear
317 * self-documenting in your code, that you are doing this in a context where you are only reading the pseudo-locked data.
318 *
319 * \note we get away with 'const' in shared_lock<const AssertExternallySynchronizedChecker> because we chose to make
320 * lock_shared, and unlock_shared const methods (see their docs above).
321 *
322 * \note - though CTOR not declared noexcept, ReadContext cannot throw an exception (it asserts out on failure)
323 */
325 static_assert (movable<ReadContext> and not copyable<ReadContext>);
326
327 public:
328 /**
329 * \brief Instantiate AssertExternallySynchronizedChecker::WriteContext to designate an area of code where protected data will be written
330 *
331 * This type alias makes a little more clear in reading code that the 'lock' is really just an assertion about thread safety
332 *
333 * Since AssertExternallySynchronizedChecker follows the concept 'mutex' you can obviously use any
334 * of the standard lockers in std::c++, but using AssertExternallySynchronizedChecker::WriteContext - makes it a little more clear
335 * self-documenting in your code, that you are doing this in a context where you are only writing the pseudo-locked data.
336 *
337 * Plus, the fact that it forces a non-const interpretation on the object in question (by using lock_guard of a non-const AssertExternallySynchronizedChecker)
338 * makes it a little easier to catch cases where you accidentally use WriteContext and meant ReadContext.
339 *
340 * \note - used lock_guard before Stroika v3.0d10, but switched to unique_lock so movable (handy in some cases).
341 * And performance not much of an issue since this is all debug-only code.
342 *
343 * \note - though CTOR not declared noexcept, WriteContext cannot throw an exception (it asserts out on failure)
344 */
346 static_assert (movable<WriteContext> and not copyable<WriteContext>);
347
348#if qStroika_Foundation_Debug_AssertExternallySynchronizedChecker_Enabled
349 private:
350 nonvirtual void lock_ () noexcept;
351 nonvirtual bool try_lock_ () noexcept;
352 nonvirtual void unlock_ () noexcept;
353 nonvirtual void lock_shared_ () const noexcept;
354 nonvirtual void unlock_shared_ () const noexcept;
355
356 private:
357 shared_ptr<SharedContext> fSharedContext_;
358
359 private:
360 static mutex& GetSharedLockMutexThreads_ (); // MUTEX ONLY FOR fSharedLocks_ (could do one mutex per AssertExternallySynchronizedChecker but static probably performs better)
361#endif
362 };
363 /*
364 * See 'Satisfies Concepts' in the class docs above.
365 *
366 * The copyable/movable half is DELIBERATE and load-bearing - do not "correct" it to match std::mutex,
367 * which is neither copyable nor movable. That difference is not an oversight, it follows from this not
368 * being a mutex: it is a checker that objects EMBED as a data member (or inherit from). Stroika is a
369 * copy-by-value framework - String, Sequence<T>, Mapping<T> and friends must stay copyable and movable -
370 * so anything they embed must be too. Deleting these operations here would make every object holding one
371 * non-copyable, which is ~181 files at last count.
372 *
373 * What copy/move actually do is check, not transfer: no lock state is carried across, and the
374 * SharedContext stays tied to the l-value. They assert the source (and for move, the target) is not
375 * locked out from under the operation - see the constructor and operator= notes above.
376 */
377 static_assert (movable<AssertExternallySynchronizedChecker> and copyable<AssertExternallySynchronizedChecker> and
379 static_assert (not movable<mutex> and not copyable<mutex>); // the contrast above, made checkable
380
381}
382
383/*
384 ********************************************************************************
385 ***************************** Implementation Details ***************************
386 ********************************************************************************
387 */
388#include "AssertExternallySynchronizedChecker.inl"
389
390#endif /*_Stroika_Foundation_Debug_AssertExternallySynchronizedChecker_h_*/
NOT a real mutex - just a debugging infrastructure support tool so in debug builds can be assured thr...
unique_lock< AssertExternallySynchronizedChecker > WriteContext
Instantiate AssertExternallySynchronizedChecker::WriteContext to designate an area of code where prot...
nonvirtual AssertExternallySynchronizedChecker & operator=(AssertExternallySynchronizedChecker &&rhs) noexcept
nonvirtual bool try_lock() noexcept
Like lock() - if it would succeed, same then, but if would fail instead of assert out,...
shared_lock< const AssertExternallySynchronizedChecker > ReadContext
Instantiate AssertExternallySynchronizedChecker::ReadContext to designate an area of code where prote...
Logically the C++ standard Lockable named requirement, but that was not included in std c++ library.
Definition StdCompat.h:96