Stroika Library 3.0d25
 
Loading...
Searching...
No Matches
Thread.cpp
1/*
2 * Copyright(c) Sophist Solutions, Inc. 1990-2026. All rights reserved
3 */
4#include "Stroika/Foundation/StroikaPreComp.h"
5
6#include "Stroika/Foundation/Common/StroikaConfig.h"
7
8#include <list>
9#include <sstream>
10#if qStroika_Platform_Windows
11#include <windows.h>
12#endif
13
18#include "Stroika/Foundation/Containers/Set.h"
20#include "Stroika/Foundation/Debug/Main.h"
24
25#include "Stroika/Foundation/Execution/Common.h"
26#include "Stroika/Foundation/Execution/DLLSupport.h"
27#include "Stroika/Foundation/Execution/Exceptions.h"
29
30#if qStroika_Platform_POSIX
31#include "Stroika/Foundation/Execution/Platform/POSIX/SignalBlock.h"
32#include "Stroika/Foundation/Execution/SignalHandlers.h"
33#endif
34#if qStroika_Platform_Windows
35#include "Stroika/Foundation/Execution/Platform/Windows/WaitSupport.h"
36#endif
37
38#include "Thread.h"
39
40using namespace Stroika::Foundation;
41
42using Containers::Set;
44
45// Comment this in to turn on aggressive noisy DbgTrace in this module
46// #define USE_NOISY_TRACE_IN_THIS_MODULE_ 1
47
48using namespace Characters;
49using namespace Execution;
50
51namespace {
52 thread_local unsigned int t_InterruptionSuppressDepth_{0};
53}
54
55#if qStroika_Foundation_Execution_Thread_SupportThreadStatistics
56namespace {
57 // use mutex and set<> to avoid interdependencies between low level Stroika facilities
58 mutex sThreadSupportStatsMutex_;
59 set<Thread::IDType> sRunningThreads_; // protected by sThreadSupportStatsMutex_
60
61 struct AllThreadsDeadDetector_ {
62 AllThreadsDeadDetector_ ()
63 {
64 Require (sRunningThreads_.empty ());
65 }
66 ~AllThreadsDeadDetector_ ()
67 {
69 if (not sRunningThreads_.empty ()) {
70 DbgTrace ("Threads {} running"_f, Thread::GetStatistics ().fRunningThreads);
71 Require (sRunningThreads_.empty ());
72 }
73 }
74 }
75 };
76 AllThreadsDeadDetector_ sAllThreadsDeadDetector_;
77}
78#endif
79
81
82#if qStroika_Platform_POSIX
83namespace {
84 Synchronized<bool> sHandlerInstalled_{false};
85}
86#endif
87
88#if qStroika_Platform_POSIX
89// Important to use direct signal handler because we send the signal to a specific thread, and must set a thread local
90// variable
91SignalHandler kCallInRepThreadAbortProcSignalHandler_ = SIG_IGN;
92#endif
93
94/*
95 ********************************************************************************
96 ************** Thread::SuppressInterruptionInContext ***************************
97 ********************************************************************************
98 */
99Thread::SuppressInterruptionInContext::SuppressInterruptionInContext ()
100{
101 ++t_InterruptionSuppressDepth_;
102}
103
104Thread::SuppressInterruptionInContext::~SuppressInterruptionInContext ()
105{
106 Assert (t_InterruptionSuppressDepth_ >= 1);
107 t_InterruptionSuppressDepth_--;
108 /*
109 * Would LIKE to do:
110 *
111 * if (t_InterruptionSuppressDepth_ == 0 and t_Interrupting_ != InterruptFlagState_::eNone) {
112 * DbgTrace ("~SuppressInterruptionInContext () completing with interruption pending, so this thread will interupt at the next cancelation point"_f);
113 * }
114 * But cannot safely/easily, because DbgTrace internally uses SuppressInterruptionInContext!
115 */
116}
117
118/*
119 ********************************************************************************
120 ************************** Thread::AbortException ******************************
121 ********************************************************************************
122 */
123Thread::AbortException::AbortException ()
124 : Exception<>{"Thread Abort"sv}
125{
126}
127
128/*
129 ********************************************************************************
130 ************************** Thread::IndexRegistrar ******************************
131 ********************************************************************************
132 */
133Thread::IndexRegistrar::IndexRegistrar ()
134{
135 Assert (not fInitialized_);
136 fInitialized_ = true;
137}
138
139Thread::IndexRegistrar::~IndexRegistrar ()
140{
141 Assert (fInitialized_);
142 fInitialized_ = false;
143}
144
145unsigned int Thread::IndexRegistrar::GetIndex (const IDType& threadID, bool* wasNew)
146{
147 if (not fInitialized_) {
148 if (wasNew != nullptr) {
149 *wasNew = false;
150 }
151 return 0;
152 }
153 [[maybe_unused]] lock_guard critSec{fMutex_};
154 auto i = fShownThreadIDs_.find (threadID);
155 unsigned int threadIndex2Show = 0;
156 if (i == fShownThreadIDs_.end ()) {
157 threadIndex2Show = static_cast<unsigned int> (fShownThreadIDs_.size ());
158 fShownThreadIDs_.insert ({threadID, threadIndex2Show});
159 }
160 else {
161 threadIndex2Show = i->second;
162 }
163 if (wasNew != nullptr) {
164 *wasNew = i == fShownThreadIDs_.end ();
165 }
166 return threadIndex2Show;
167}
168
169/*
170 ********************************************************************************
171 ***************************** Thread::Ptr::Rep_ ********************************
172 ********************************************************************************
173 */
174Thread::Ptr::Rep_::Rep_ (const function<void ()>& runnable, [[maybe_unused]] const optional<Configuration>& configuration)
175 : fRunnable_{runnable}
176{
177 // @todo - never used anything from configuration (yet) - should!)
178#if qStroika_Platform_POSIX
179 static bool sDidInit_{false}; // initialize after main() started, but before any threads
180 if (not sDidInit_) {
181 sDidInit_ = true;
182 kCallInRepThreadAbortProcSignalHandler_ = SignalHandler{Rep_::InterruptionSignalHandler_, SignalHandler::Type::eDirect};
183 }
184#elif qStroika_Platform_Windows
185 if (configuration.has_value () and configuration->fThrowInterruptExceptionInsideUserAPC.has_value ()) {
186 fThrowInterruptExceptionInsideUserAPC_ = configuration->fThrowInterruptExceptionInsideUserAPC.value ();
187 }
188#endif
189}
190
191Thread::Ptr::Rep_::~Rep_ ()
192{
193 /*
194 * Use thread::detach() - since this could be called from another thread, or from the
195 * thread which fThread_ refers to. Calling from the later case thread would deadlock
196 * and is a C++ error to call.
197 *
198 * thread::detach will cause all resources for the thread to be deleted once the thread
199 * terminates.
200 *
201 * From http://en.cppreference.com/w/cpp/thread/thread/detach:
202 * Separates the thread of execution from the thread object, allowing execution to continue
203 * independently. Any allocated resources will be freed once the thread exits.
204 *
205 * no need for lock_guard<mutex> critSec { fAccessSTDThreadMutex_ }; because if destroying, only one thread can reference this smart-ptr
206 */
207 if (fThreadValid_ and fThread_.joinable ()) {
208 fThread_.detach ();
209 }
210}
211
212void Thread::Ptr::Rep_::Run_ ()
213{
214 try {
215 fRunnable_ ();
216 }
217 catch (const AbortException&) {
218 // Note: intentionally not saved in fSavedException_.
219 // See ThrowIfDoneWithException
220 throw;
221 }
222 catch (...) {
223#if USE_NOISY_TRACE_IN_THIS_MODULE_
224 DbgTrace ("in Thread::Ptr::Rep_::Run_ () - saving caught exception to repropagate later ({})"_f, current_exception ());
225#endif
226 fSavedException_ = current_exception ();
227 throw;
228 }
229}
230
231// [[nosanitize thread]] because PeekIsSet () - intentionally - reads without a lock
232Stroika_Foundation_Debug_ATTRIBUTE_NO_SANITIZE_THREAD Characters::String Thread::Ptr::Rep_::ToString () const
233{
234 StringBuilder sb;
235 sb << "{"sv;
236 if (fRefCountBumpedInsideThreadMainEvent_.PeekIsSet ()) {
237 // If fRefCountBumpedInsideThreadMainEvent_ not yet SET, then this info is bogus
238 sb << "id: "sv << GetID ();
240 sb << ", index: " << IndexRegistrar::sThe.GetIndex (GetID ());
241 }
242 }
243 if (not fThreadName_.empty ()) {
244 sb << ", name: "sv << fThreadName_;
245 }
246 sb << ", status: "sv << PeekStatusForToString_ ();
247 //sb << ", runnable: "sv << fRunnable_; // doesn't yet print anything useful
248 sb << ", abortRequested: "sv << fAbortRequested_.load ();
249 sb << ", refCountBumpedEvent: "sv << fRefCountBumpedInsideThreadMainEvent_.PeekIsSet ();
250 sb << ", startReadyToTransitionToRunningEvent_: "sv << fStartReadyToTransitionToRunningEvent_.PeekIsSet ();
251 sb << ", threadDoneAndCanJoin: "sv << fThreadDoneAndCanJoin_.PeekIsSet ();
252 if (fSavedException_.load () != nullptr) [[unlikely]] {
253 sb << ", savedException: "sv << fSavedException_.load ();
254 }
255 if (fInitialPriority_.load () != nullopt) [[unlikely]] {
256 sb << ", initialPriority: "sv << fInitialPriority_.load ();
257 }
258#if qStroika_Platform_Windows
259 sb << ", throwInterruptExceptionInsideUserAPC: "sv << fThrowInterruptExceptionInsideUserAPC_;
260#endif
261 sb << "}"sv;
262 return sb;
263}
264
265void Thread::Ptr::Rep_::ApplyThreadName2OSThreadObject ()
266{
267 if (GetNativeHandle () != NativeHandleType{}) {
268#if qStroika_Platform_Windows
269 (void)::SetThreadDescription (GetNativeHandle (), fThreadName_.c_str ()); // ignore errors - just so stuff shows in debugger, but might not have permission to set
270#elif qStroika_Platform_POSIX && (__GLIBC__ > 2 or (__GLIBC__ == 2 and __GLIBC_MINOR__ >= 12))
271 // could have called prctl(PR_SET_NAME,"<null> terminated string",0,0,0) - but seems less portable
272 //
273 // according to http://man7.org/linux/man-pages/man3/pthread_setname_np.3.html - the length max is 15 characters
274 constexpr size_t kMaxNameLen_{16 - 1}; // 16 chars including nul byte
275 string narrowThreadName = String{fThreadName_}.AsNarrowSDKString (eIgnoreErrors);
276 if (narrowThreadName.length () > kMaxNameLen_) {
277 narrowThreadName.erase (kMaxNameLen_);
278 }
279 ::pthread_setname_np (GetNativeHandle (), narrowThreadName.c_str ());
280#endif
281 }
282}
283
284void Thread::Ptr::Rep_::ApplyPriority (Priority priority)
285{
286#if USE_NOISY_TRACE_IN_THIS_MODULE_
288 "Thread::Ptr::Rep_::ApplyPriority", "threads={}, priority={}"_f, Characters::ToString (*this), Characters::ToString (priority))};
289#endif
290 NativeHandleType nh = GetNativeHandle ();
291 if (nh != NativeHandleType{}) {
292#if qStroika_Platform_Windows
293 switch (priority) {
294 case Priority::eLowest:
295 Verify (::SetThreadPriority (nh, THREAD_PRIORITY_LOWEST));
296 break;
297 case Priority::eBelowNormal:
298 Verify (::SetThreadPriority (nh, THREAD_PRIORITY_BELOW_NORMAL));
299 break;
300 case Priority::eNormal:
301 Verify (::SetThreadPriority (nh, THREAD_PRIORITY_NORMAL));
302 break;
303 case Priority::eAboveNormal:
304 Verify (::SetThreadPriority (nh, THREAD_PRIORITY_ABOVE_NORMAL));
305 break;
306 case Priority::eHighest:
307 Verify (::SetThreadPriority (nh, THREAD_PRIORITY_HIGHEST));
308 break;
309 default:
311 }
312#elif qStroika_Platform_POSIX
313 /*
314 * pthreads - use http://man7.org/linux/man-pages/man3/pthread_getschedparam.3.html
315 *
316 * Linux notes:
317 * From http://man7.org/linux/man-pages/man7/sched.7.html
318 *
319 * Since Linux 2.6.23, the default scheduler is CFS, the "Completely
320 * Fair Scheduler". The CFS scheduler replaced the earlier "O(1)"
321 * scheduler.
322 *
323 * ...
324 *
325 * For threads scheduled under one of the normal scheduling policies
326 * (SCHED_OTHER, SCHED_IDLE, SCHED_BATCH), sched_priority is not used in
327 * scheduling decisions (it must be specified as 0).
328 *
329 * So - bottom line - this is a complete waste of time.
330 */
331 int priorityMin;
332 int priorityMax;
333 int schedulingPolicy{}; // on Linux, this appears to always be 0 - SCHED_OTHER, so cannot set priorities
334 {
335 sched_param param{};
336 Verify (::pthread_getschedparam (nh, &schedulingPolicy, &param) == 0);
337 priorityMin = ::sched_get_priority_min (schedulingPolicy);
338 priorityMax = ::sched_get_priority_max (schedulingPolicy);
339#if USE_NOISY_TRACE_IN_THIS_MODULE_
340 DbgTrace ("schedulingPolicy={}, default-priority={}, sPriorityMin_={}, priorityMax={}"_f, schedulingPolicy,
341 param.sched_priority, priorityMin, priorityMax);
342#endif
343 }
344 int newPThreadPriority{priorityMin};
345 switch (priority) {
346 case Priority::eLowest:
347 newPThreadPriority = priorityMin;
348 break;
349 case Priority::eBelowNormal:
350 newPThreadPriority = (priorityMax - priorityMin) * .25 + priorityMin;
351 break;
352 case Priority::eNormal:
353 newPThreadPriority = (priorityMax - priorityMin) * .5 + priorityMin;
354 break;
355 case Priority::eAboveNormal:
356 newPThreadPriority = (priorityMax - priorityMin) * .75 + priorityMin;
357 break;
358 case Priority::eHighest:
359 newPThreadPriority = priorityMax;
360 break;
361 default:
363 newPThreadPriority = (priorityMax - priorityMin) * .5 + priorityMin;
364 }
365#if USE_NOISY_TRACE_IN_THIS_MODULE_
366 DbgTrace ("Setting os thread priority for thread %{} to %{}"_f, (long long int)(nh), newPThreadPriority);
367#endif
368 /*
369 * \note Slightly simpler to use POSIX pthread_setschedprio - http://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_setschedprio.html
370 * but alas MacOSX (XCode 10) doesn't support this, so keep more common code, and use about the same process - pthread_setschedparam
371 */
372 sched_param sp{};
373 sp.sched_priority = newPThreadPriority;
374 Verify (::pthread_setschedparam (nh, schedulingPolicy, &sp) == 0 or errno == EPERM);
375#else
376 // Cannot find any way todo this
378#endif
379 }
380}
381
382void Thread::Ptr::Rep_::ThreadMain_ (const shared_ptr<Rep_> thisThreadRep) noexcept
383{
384 RequireNotNull (thisThreadRep); // NOTE - since shared_ptr<> is NOT a const reference, this holds the bumped reference count til the end of ThreadMain_ scope
385 TraceContextBumper ctx{Stroika_Foundation_Debug_OptionalizeTraceArgs ("Thread::Ptr::Rep_::ThreadMain_", "thisThreadRep={}"_f,
386 Characters::ToString (thisThreadRep))};
387#if qStroika_Foundation_Debug_AssertionsChecked
388 Require (Debug::AppearsDuringMainLifetime ());
389 [[maybe_unused]] auto&& cleanupCheckMain = Finally ([] () noexcept { Require (Debug::AppearsDuringMainLifetime ()); });
390#endif
391
392 try {
393 {
394 SuppressInterruptionInContext suppressInterruptionsOfThisThreadCallerKnowsWeHaveItBumpedAndCanProceed;
395 // This thread (ThreadMain) cannot possibly get interrupted BEFORE this - because only after this fRefCountBumpedInsideThreadMainEvent_ does the rest of the APP know about our thread ID
396 // baring an external process sending us a bogus signal)
397 //
398 // Note that BOTH the fRefCountBumpedInsideThreadMainEvent_ and the fStartReadyToTransitionToRunningEvent_ wait MUST come inside the try/catch for
399 thisThreadRep->fRefCountBumpedInsideThreadMainEvent_.Set ();
400 }
401
402 // So inside 'Run' - we will have access to this thread_local variable
403#if qCompilerAndStdLib_thread_local_static_inline_twice_Buggy
404 sCurrentThreadRep_BWA_ () = thisThreadRep;
405#else
406 sCurrentThreadRep_ = thisThreadRep;
407#endif
408
409 [[maybe_unused]] IDType thisThreadID = GetCurrentThreadID (); // NOTE - CANNOT call thisThreadRep->GetID () or in any way touch thisThreadRep->fThread_
410
411#if qStroika_Foundation_Execution_Thread_SupportThreadStatistics
412 {
413 Require (Debug::AppearsDuringMainLifetime ());
414 [[maybe_unused]] lock_guard critSec{sThreadSupportStatsMutex_};
415#if qStroika_Foundation_Debug_ShowThreadIndex
416 DbgTrace (
417 "Adding thread index {} to sRunningThreads_ ({})"_f, IndexRegistrar::sThe.GetIndex (thisThreadID),
418 Traversal::Iterable<IDType>{sRunningThreads_}.Map<vector<int>> ([] (IDType i) { return IndexRegistrar::sThe.GetIndex (i); }));
419#else
420 DbgTrace ("Adding thread id {} to sRunningThreads_ ({})"_f, thisThreadID, sRunningThreads_);
421#endif
422 Verify (sRunningThreads_.insert (thisThreadID).second); // .second true if inserted, so checking not already there
423 }
424 [[maybe_unused]] auto&& cleanup = Finally ([thisThreadID] () noexcept {
425 SuppressInterruptionInContext suppressThreadInterrupts; // may not be needed, but safer/harmless
426 Require (Debug::AppearsDuringMainLifetime ()); // Note: A crash in this code is FREQUENTLY the result of an attempt to destroy a thread after existing main () has started
427 [[maybe_unused]] lock_guard critSec{sThreadSupportStatsMutex_};
428#if qStroika_Foundation_Debug_ShowThreadIndex
429 DbgTrace (
430 "removing thread index {} from sRunningThreads_ ({})"_f, IndexRegistrar::sThe.GetIndex (thisThreadID),
431 Traversal::Iterable<IDType>{sRunningThreads_}.Map<vector<int>> ([] (IDType i) { return IndexRegistrar::sThe.GetIndex (i); }));
432#else
433 DbgTrace ("removing thread id {} from sRunningThreads_ ({})"_f, thisThreadID, sRunningThreads_);
434#endif
435 Verify (sRunningThreads_.erase (thisThreadID) == 1); // verify exactly one erased
436 });
437#endif
438
439 try {
440#if qStroika_Platform_POSIX
441 {
442 // we inherit blocked abort signal given how we are created in DoCreate() - so unblock it -
443 // and accept aborts after we've marked reference count as set.
444 sigset_t mySet;
445 sigemptyset (&mySet); // nb: cannot use :: cuz crapple uses macro --LGP 2016-12-31
446 (void)sigaddset (&mySet, SignalUsedForThreadInterrupt ()); // ""
447 Verify (::pthread_sigmask (SIG_UNBLOCK, &mySet, nullptr) == 0);
448#if USE_NOISY_TRACE_IN_THIS_MODULE_
449 DbgTrace ("Just set SIG_UNBLOCK for signal {} in this thread"_f, SignalToName (SignalUsedForThreadInterrupt ()));
450#endif
451 }
452#endif
453 thisThreadRep->fStartReadyToTransitionToRunningEvent_.Wait ();
454
455 [[maybe_unused]] auto&& cleanupThreadDoneEventSetter = Finally ([thisThreadRep] () noexcept {
456 // whether aborted before we transition state to running, or after, be sure to set this so we can 'join' the thread (also done in catch handlers)
457 thisThreadRep->fThreadDoneAndCanJoin_.Set ();
458 });
459
460 Assert (thisThreadID == thisThreadRep->GetID ()); // By now we know thisThreadRep->fThread_ has been assigned so it can be accessed
461
462 if (not thisThreadRep->fAbortRequested_ and not thisThreadRep->IsDone_ ()) {
463#if defined(__cpp_lib_jthread)
464 // If a caller uses the std stop_token mechanism, assure the thread is marked as stopped/aborted
465 // But only register this after fRefCountBumpedInsideThreadMainEvent_ (would need to think more carefully to place this earlier)
466 // --LGP 2023-10-03
467 stop_callback stopCallback{thisThreadRep->fStopToken_, [=] () {
468 Debug::TraceContextBumper ctx1{"Thread::Ptr::Rep_::ThreadMain_ - stop_callback"};
469 if (thisThreadRep->fAbortRequested_) [[likely]] {
470 DbgTrace ("skipped abort cuz done already"_f);
471 }
472 else {
473 DbgTrace ("Something triggered stop_token request stop, so doing abort to make sure we are in an aborting (flag) state."_f);
474 // Abort () call is is slightly overkill, since frequently already in the aborting state, so check first
475 IgnoreExceptionsForCall (Ptr{thisThreadRep}.Abort ());
476 }
477 }};
478#endif
479 DbgTrace ("In Thread::Rep_::ThreadMain_ - set state to RUNNING for thread: {}"_f, thisThreadRep->ToString ());
480 thisThreadRep->Run_ ();
481 DbgTrace ("In Thread::Rep_::ThreadProc_ - setting state to COMPLETED for thread: {}"_f, thisThreadRep->ToString ());
482 }
483 }
484 catch (const AbortException&) {
485 SuppressInterruptionInContext suppressCtx;
486 DbgTrace ("In Thread::Rep_::ThreadProc_ - setting state to COMPLETED (InterruptException) for thread: {}"_f, thisThreadRep->ToString ());
487 thisThreadRep->fThreadDoneAndCanJoin_.Set ();
488 }
489 catch (...) {
490 SuppressInterruptionInContext suppressCtx;
491 DbgTrace ("In Thread::Rep_::ThreadProc_ - setting state to COMPLETED (due to EXCEPTION) for thread: {}"_f, thisThreadRep->ToString ());
492 thisThreadRep->fThreadDoneAndCanJoin_.Set ();
493 }
494 }
495 catch (const AbortException&) {
496 DbgTrace ("SERIOUS ERROR in Thread::Rep_::ThreadMain_ () - uncaught InterruptException - see sigsetmask stuff above - somehow not "
497 "working???"_f);
498 AssertNotReached (); // This should never happen - but if it does - better a trace message in a tracelog than 'unexpected' being called (with no way out)
499 }
500 catch (...) {
501 DbgTrace ("SERIOUS ERROR in Thread::Rep_::ThreadMain_ () - uncaught exception"_f);
502 AssertNotReached (); // This should never happen - but if it does - better a trace message in a tracelog than 'unexpected' being called (with no way out)
503 }
504}
505
506void Thread::Ptr::Rep_::NotifyOfInterruptionFromAnyThread_ ()
507{
508 /*
509 * The thread may already be done - or finish while we are in here. Abort () sets fAbortRequested_ BEFORE it checks
510 * IsDone (), and the target thread can see that flag (any CheckForInterruption) and run to completion at any moment
511 * after, so Abort's IsDone () check is only an optimization. So everything below must be harmless on a finished thread.
512 * (This was a Require (not IsDone_ ()), which failed sporadically in Test40 on every platform 2024-2026).
513 */
514 Require (fAbortRequested_);
515 //TraceContextBumper ctx{"Thread::Rep_::NotifyOfAbortFromAnyThread_"};
516
517 // typically abort from another thread, but in principle this could happen!
518 if (GetCurrentThreadID () == GetID ()) [[unlikely]] {
519 CheckForInterruption (); // unless suppressed, this will throw
520 }
521
522 // Note we fall through here either if we have throws suppressed, or if sending to another thread
523
524 // if fThreadValid_, and can try to cancel it; else start () process early enuf it will cancel
525 if (fThreadValid_) {
526 /*
527 * Do some platform-specific magic to terminate ongoing system calls
528 *
529 * On POSIX - this is sending a signal which generates EINTR error.
530 * On Windoze - this is QueueUserAPC to enter an alertable state.
531 */
532#if qStroika_Platform_POSIX
533 {
534 [[maybe_unused]] lock_guard critSec{sHandlerInstalled_};
535 if (not sHandlerInstalled_) {
536 SignalHandlerRegistry::sThe.AddSignalHandler (SignalUsedForThreadInterrupt (), kCallInRepThreadAbortProcSignalHandler_);
537 sHandlerInstalled_ = true;
538 }
539 }
540 (void)SendSignal (GetNativeHandle (), SignalUsedForThreadInterrupt ()); // ESRCH if the thread has exited - fine
541#elif qStroika_Platform_Windows
542 if (not ::QueueUserAPC (&CalledInRepThreadAbortProc_, GetNativeHandle (), reinterpret_cast<ULONG_PTR> (this))) [[unlikely]] {
543 // fails (ERROR_GEN_FAILURE) once the thread has exited - fine, nothing left to interrupt
544 Assert (IsDone_ ());
545 }
546#endif
547 }
548}
549
550#if qStroika_Platform_POSIX
551void Thread::Ptr::Rep_::InterruptionSignalHandler_ (SignalID signal) noexcept
552{
553 //
554 //#if USE_NOISY_TRACE_IN_THIS_MODULE_
555 // unsafe to call trace code - because called as unsafe (SignalHandler::Type::eDirect) handler
556 //TraceContextBumper ctx{"Thread::Ptr::Rep_::InterruptionSignalHandler_"};
557 //#endif
558 // This doesn't REALLY need to get called. Its enough to have the side-effect of the EINTR from system calls.
559 // the TLS variable gets set through the rep pointer in NotifyOfInterruptionFromAnyThread_
560 //
561 // Note - using SIG_IGN doesn't work, because then the signal doesn't get delivered, and the EINTR doesn't happen
562 //
563}
564#elif qStroika_Platform_Windows
565void CALLBACK Thread::Ptr::Rep_::CalledInRepThreadAbortProc_ (ULONG_PTR lpParameter)
566{
567 TraceContextBumper ctx{"Thread::Ptr::Rep_::CalledInRepThreadAbortProc_"};
568 [[maybe_unused]] Ptr::Rep_* rep = reinterpret_cast<Ptr::Rep_*> (lpParameter);
569 Require (GetCurrentThreadID () == rep->GetID ());
570 if (rep->fThrowInterruptExceptionInsideUserAPC_) [[unlikely]] {
572 }
573}
574#endif
575
576/*
577 ********************************************************************************
578 ******************************** Thread::Ptr ***********************************
579 ********************************************************************************
580 */
581namespace {
582 Synchronized<Thread::Configuration> sDefaultConfiguration_;
583}
584
585namespace {
586 Thread::Configuration CombineCFGs_ (const optional<Thread::Configuration>& cfg)
587 {
589 if (cfg) {
590 if (cfg->fStackSize) {
591 result.fStackSize = *cfg->fStackSize;
592 }
593 if (cfg->fStackGuard) {
594 result.fStackSize = *cfg->fStackGuard;
595 }
596#if qStroika_Platform_Windows
597 if (cfg->fThrowInterruptExceptionInsideUserAPC) {
598 result.fThrowInterruptExceptionInsideUserAPC = *cfg->fThrowInterruptExceptionInsideUserAPC;
599 }
600#endif
601 }
602 return result;
603 }
604}
605
607{
608 RequireNotNull (fRep_);
609 AssertExternallySynchronizedChecker::ReadContext declareContext{fThisAssertExternallySynchronized_}; // smart ptr - its the ptr thats const, not the rep
611 if (nh == NativeHandleType{}) {
612 // This can happen if you set the thread priority before starting the thread (actually probably a common sequence of events)
613 fRep_->fInitialPriority_.store (priority);
614 return;
615 }
616 else {
617 fRep_->ApplyPriority (priority);
618 }
619}
620
622{
623 AssertExternallySynchronizedChecker::ReadContext declareContext{fThisAssertExternallySynchronized_};
624 return fRep_ == nullptr ? String{} : fRep_->fThreadName_;
625}
626
627void Thread::Ptr::SetThreadName (const String& threadName) const
628{
629 RequireNotNull (fRep_);
630 AssertExternallySynchronizedChecker::ReadContext declareContext{fThisAssertExternallySynchronized_}; // smart ptr - its the ptr thats const, not the rep
631#if USE_NOISY_TRACE_IN_THIS_MODULE_
632 TraceContextBumper ctx{"Thread::SetThreadName", "thisThreadID={}, threadName = '{}'"_f, GetID (), threadName};
633#endif
634 if (fRep_->fThreadName_ != threadName) {
635 fRep_->fThreadName_ = threadName.As<wstring> ();
636 fRep_->ApplyThreadName2OSThreadObject ();
637 }
638}
639
641{
642 AssertExternallySynchronizedChecker::ReadContext declareContext{fThisAssertExternallySynchronized_};
643 return fRep_ == nullptr ? "nullptr"sv : fRep_->ToString ();
644}
645
647{
648 AssertExternallySynchronizedChecker::ReadContext declareContext{fThisAssertExternallySynchronized_}; // smart ptr - its the ptr thats const, not the rep
649 Debug::TraceContextBumper ctx{"Thread::Start", "*this={}"_f, ToString ()};
650 RequireNotNull (fRep_);
651 Require (not fRep_->fStartEverInitiated_);
652#if qStroika_Foundation_Debug_AssertionsChecked
653 {
654 auto s = GetStatus (); // @todo - consider - not sure about this
655 Require (s == Status::eNotYetRunning or s == Status::eAborting); // if works - document
656 }
657#endif
658
659 /*
660 * Stroika thread-start choreography:
661 *
662 * CALLING_THREAD | STATE CREATED THREAD
663 * Create 'shared_ptr<Rep>' <| eNotYetRunning
664 * (notes - anytime after state set to eNotYetRunning can transition to eAborting. Only from eRunning or eAborting can it transition to eCompleted )
665 * ENTER CALL TO Thread::Ptr::Start () <|
666 * START SuppressInterruptionInContext <|
667 * Create jthread object, giving it <|
668 * a 'ThreadMain' <|
669 * WAIT ON fRefCountBumpedInsideThreadMainEvent_ <|> ENTER Rep_::ThreadMain_ with BUMPED shared_ptr<Rep> refcount
670 * |> thisThreadRep->fRefCountBumpedInsideThreadMainEvent_.Set () (NOTE thisThreadRep == fRefCountBumpedInsideThreadMainEvent_)
671 * END SuppressInterruptionInContext |
672 * Setup a few thread properties, name, priority <|> Setup thread-local properties, inside ThreadMain/new thread
673 * fRep_->fStartReadyToTransitionToRunningEvent_.Set ()<|> thisThreadRep->fStartReadyToTransitionToRunningEvent_.Wait (); -- NOTE CANNOT ACCESS thisThreadRep->fThread_ until this point
674 * return/done <|> eRunning|(etc) STATE TRANSITION TO RUNNING (MAYBE - COULD HAVE BEEN ALREADY ABORTED)
675 */
676
677 {
678 /*
679 * Once we have constructed the other thread, its critical it be allowed to run at least to the
680 * point where it's bumped its reference count before we allow aborting this thread.
681 */
682 SuppressInterruptionInContext suppressInterruptionsOfThisThreadWhileConstructingRepOtherElseLoseSharedPtrEtc;
683
684 fRep_->fStartEverInitiated_ = true; //atomic/publish
685 if (fRep_->fAbortRequested_) [[unlikely]] {
686 Throw (Execution::Exception<runtime_error>{"Thread aborted during start"sv}); // check and if aborting now, don't go further
687 }
688
689#if defined(__cpp_lib_jthread)
690 fRep_->fStopToken_ = fRep_->fStopSource_.get_token ();
691 fRep_->fThread_ = jthread{[this] () -> void { Rep_::ThreadMain_ (fRep_); }};
692#else
693 fRep_->fThread_ = thread{[this] () -> void { Rep_::ThreadMain_ (fRep_); }};
694#endif
695 fRep_->fThreadValid_ = true;
696
697 // assure we wait for this, so we don't ever let refcount go to zero before the thread has started.
698 fRep_->fRefCountBumpedInsideThreadMainEvent_.Wait ();
699
700 // Once we've gotten here, the ThreadMain is executing, but 'paused' waiting for us to setup more stuff
701 }
702
703 // Setup a few thread properties, name, priority
704 fRep_->ApplyThreadName2OSThreadObject ();
705 if (optional<Priority> p = fRep_->fInitialPriority_.load ()) {
706 fRep_->ApplyPriority (*p);
707 }
708 DbgTrace ("Requesting transition to running for {}"_f, ToString ());
709 fRep_->fStartReadyToTransitionToRunningEvent_.Set ();
710}
711void Thread::Ptr::Start (WaitUntilStarted) const
712{
713 Start ();
714 for (auto s = GetStatus (); s != Status::eNotYetRunning; s = GetStatus ()) {
715 // @todo fix this logic - set explicit when we do the SET EVENT above (before). But then need to change the threadmain logic to accommodate;
716 // low priority since this overload probably not used...
717 // --LGP 2023-11-30
718 this_thread::yield ();
719 }
720#if qStroika_Foundation_Debug_AssertionsChecked
721 auto s = GetStatus ();
722 Ensure (s == Status::eRunning or s == Status::eAborting or s == Status::eCompleted);
723#endif
724}
725
727{
729 Require (*this != nullptr);
730 AssertExternallySynchronizedChecker::ReadContext declareContext{fThisAssertExternallySynchronized_}; // smart ptr - its the ptr thats const, not the rep
731
732#if defined(__cpp_lib_jthread)
733 bool wasAborted = fRep_->fAbortRequested_;
734#endif
735 // Abort can be called with status in ANY state, except nullptr (which would mean ever assigned Thread::New());
736 fRep_->fAbortRequested_ = true;
737 if (fRep_->fStartEverInitiated_) {
738#if defined(__cpp_lib_jthread)
739 // If transitioning to aborted state, notify any existing stop_callbacks
740 // not needed to check prevState - since https://en.cppreference.com/w/cpp/thread/jthread/request_stop says requst_stop checks if already requested.
741 if (not wasAborted) [[likely]] {
742 DbgTrace ("Transitioned state to aborting, so calling fThread_.get_stop_source ().request_stop ();"_f);
743 fRep_->fStopSource_.request_stop ();
744 }
745#endif
746 }
747 else {
748 /*
749 * Then mark the thread as completed.
750 *
751 * If we have not yet called start (or gotten to the point where fStartEverInitiated_ gets set), then set the CanJoin event.
752 * sb safe.
753 */
754 fRep_->fThreadDoneAndCanJoin_.Set ();
755 }
756 if (not IsDone ()) [[likely]] {
757 // by default - tries to trigger a throw-abort-exception in the right thread using UNIX signals or QueueUserAPC ()
758 fRep_->NotifyOfInterruptionFromAnyThread_ ();
759 }
760#if USE_NOISY_TRACE_IN_THIS_MODULE_
761 DbgTrace ("leaving *this = {}"_f, *this);
762#endif
763}
764
766{
767 Debug::TraceContextBumper ctx{Stroika_Foundation_Debug_OptionalizeTraceArgs ("Thread::AbortAndWaitForDoneUntil",
768 "*this={}, timeoutAt={}"_f, ToString (), timeoutAt)};
769 RequireNotNull (*this);
770 AssertExternallySynchronizedChecker::ReadContext declareContext{fThisAssertExternallySynchronized_};
771
772 /*
773 * One Abort () is enough, and this deliberately does not re-send - @see the note on
774 * Thread::Ptr::AbortAndWaitForDoneUntil () in Thread.h for why. Stroika before v3 re-sent; removed on purpose.
775 */
776 Abort ();
777 WaitForDoneUntil (timeoutAt);
778}
779
781{
782#if USE_NOISY_TRACE_IN_THIS_MODULE_
783 Debug::TraceContextBumper ctx{"Thread::ThrowIfDoneWithException", "*this={}"_f, *this};
784#endif
785 AssertExternallySynchronizedChecker::ReadContext declareContext{fThisAssertExternallySynchronized_};
786 if (fRep_ and fRep_->IsDone_ () and fRep_->fSavedException_.load () != nullptr) {
787 // safe not holding lock cuz code simpler, and cannot transition from savedExcept to none - never cleared
788 ReThrow (fRep_->fSavedException_.load (), "Rethrowing exception across threads");
789 }
790}
791
793{
794 Debug::TraceContextBumper ctx{"Thread::WaitForDoneUntil", "*this={}, timeoutAt={}"_f, ToString (), timeoutAt};
795 if (not WaitForDoneUntilQuietly (timeoutAt)) {
796 ThrowError (errc::timed_out);
797 }
798}
799
801{
802#if USE_NOISY_TRACE_IN_THIS_MODULE_
804 "*this={}, timeoutAt={}"_f, ToString (), timeoutAt)};
805#endif
806 Require (*this != nullptr);
807 AssertExternallySynchronizedChecker::ReadContext declareContext{fThisAssertExternallySynchronized_};
808 CheckForInterruption (); // always a cancelation point
809 if (fRep_->fThreadDoneAndCanJoin_.WaitUntilQuietly (timeoutAt) == WaitableEvent::WaitStatus::eTriggered) {
810 /*
811 * This is not critical, but has the effect of assuring the COUNT of existing threads is what the caller would expect.
812 * This really only has effect #if qStroika_Foundation_Execution_Thread_SupportThreadStatistics
813 * because that's the only time we have an important side effect of the threads finalizing.
814 *
815 * @see https://github.com/SophistSolutions/Stroika/issues/630 (STK-496)
816 *
817 * NOTE: because we call this join () inside fAccessSTDThreadMutex_, its critical the running thread has terminated to the point where it will no
818 * longer access fThread_ (and therefore not lock fAccessSTDThreadMutex_)
819 */
820 if (fRep_->fThreadValid_ and fRep_->fThread_.joinable ()) {
821 // fThread_.join () will block indefinitely - but since we waited on fRep_->fThreadDoneAndCanJoin_ - it shouldn't really take long
822 fRep_->fThread_.join ();
823 }
824 return true;
825 }
826 Assert (timeoutAt <= Time::GetTickCount ()); // otherwise we couldn't have timed out
827 return false;
828}
829
830#if qStroika_Platform_Windows
831void Thread::Ptr::WaitForDoneWhilePumpingMessages (Time::DurationSeconds timeout) const
832{
833 AssertExternallySynchronizedChecker::ReadContext declareContext{fThisAssertExternallySynchronized_};
834 Require (*this != nullptr);
836 HANDLE thread = fRep_->GetNativeHandle ();
837 if (thread == INVALID_HANDLE_VALUE) {
838 return;
839 }
840 Time::TimePointSeconds timeoutAt = Time::GetTickCount () + timeout;
841 // CRUDDY impl - but decent enuf for first draft
842 while (GetStatus () != Status::eCompleted) {
843 Time::DurationSeconds time2Wait = timeoutAt - Time::GetTickCount ();
844 if (time2Wait <= 0s) {
845 ThrowError (errc::timed_out);
846 }
847 Platform::Windows::WaitAndPumpMessages (nullptr, {thread}, time2Wait);
848 }
849 WaitForDone (); // just to get the qStroika_Foundation_Execution_Thread_SupportThreadStatistics / join ()
850}
851#endif
852
853/*
854 ********************************************************************************
855 **************************** Thread::CleanupPtr ********************************
856 ********************************************************************************
857 */
858Thread::CleanupPtr::~CleanupPtr ()
859{
860 /*
861 * The wait below is deliberately unbounded (@see the kInfinity default on AbortAndWaitForDone). The
862 * entire point of this class is to guarantee the thread is finished before whatever it holds pointers
863 * into gets destroyed; a bounded wait would trade that guarantee for a still-running thread and no way
864 * left to recover from it.
865 *
866 * So if this appears to hang - or dies in std::terminate, destructors being noexcept, which makes any
867 * throw out of the wait fatal - the fault is NOT here. It means the thread did not stop when it was
868 * asked to. Look upstream, at what the thread was blocked in and at whether the abort actually reached
869 * it; do not look at this destructor, and do not "fix" it by bounding the wait.
870 */
871 if (*this != nullptr) {
872 SuppressInterruptionInContext suppressInterruption;
873 if (fAbort_) {
875 }
876 else {
877 WaitForDone ();
878 }
879 }
880}
881
882/*
883 ********************************************************************************
884 *********************************** Thread *************************************
885 ********************************************************************************
886 */
887Thread::Ptr Thread::New (const function<void ()>& fun2CallOnce, const optional<Characters::String>& name, const optional<Configuration>& configuration)
888{
889 // All Thread::New () overloads vector through this one...
890 Ptr ptr = Ptr{Memory::MakeSharedPtr<Ptr::Rep_> (fun2CallOnce, CombineCFGs_ (configuration))};
891 if (name) {
892 ptr.SetThreadName (*name);
893 }
894 return ptr;
895}
896
898{
899 return sDefaultConfiguration_.load ();
900}
901
902Thread::Configuration Thread::DefaultConfiguration (const optional<Configuration>& newConfiguration)
903{
904 auto result = sDefaultConfiguration_.load ();
905 if (newConfiguration) {
906 sDefaultConfiguration_.store (newConfiguration.value ());
907 }
908 return result;
909}
910
911#if qStroika_Foundation_Execution_Thread_SupportThreadStatistics
912Thread::Statistics Thread::GetStatistics ()
913{
914 [[maybe_unused]] lock_guard critSec{sThreadSupportStatsMutex_};
915 return Statistics{Containers::Set<IDType>{sRunningThreads_}};
916}
917#endif
918
920{
921#if USE_NOISY_TRACE_IN_THIS_MODULE_
922 Debug::TraceContextBumper ctx{"Thread::Abort", "threads={}"_f, threads};
923#endif
924 threads.Apply ([] (Ptr t) { t.Abort (); });
925}
926
928{
929#if USE_NOISY_TRACE_IN_THIS_MODULE_
930 Debug::TraceContextBumper ctx{Stroika_Foundation_Debug_OptionalizeTraceArgs ("Thread::AbortAndWaitForDoneUntil",
931 "threads={}, timeoutAt={}"_f, threads, timeoutAt)};
932#endif
933 /*
934 * Before Stroika v3, we would sometimes re-send the abort message, but no need if this is not buggy. One abort sb enuf.
935 */
936 Abort (threads);
937 WaitForDoneUntil (threads, timeoutAt);
938}
939
941{
942#if USE_NOISY_TRACE_IN_THIS_MODULE_
943 Debug::TraceContextBumper ctx{"Thread::WaitForDoneUntil", "threads={}, timeoutAt={}"_f, threads, timeoutAt};
944#endif
945 CheckForInterruption (); // always a cancelation point (even if empty list)
946 // consider rewriting so we don't do this sequentially, but 'harvest' the ones completed (much as we did in Stroika v2.1), but perhaps no point.
947 // This is probably fine.
948 threads.Apply ([timeoutAt] (const Ptr& t) { t.WaitForDoneUntil (timeoutAt); });
949}
950
951#if qStroika_Platform_POSIX
952namespace {
953 SignalID sSignalUsedForThreadInterrupt_ = SIGUSR2;
954}
955SignalID Thread::SignalUsedForThreadInterrupt () noexcept
956{
957 return sSignalUsedForThreadInterrupt_;
958}
959SignalID Thread::SignalUsedForThreadInterrupt (optional<SignalID> signalNumber)
960{
961 SignalID result = sSignalUsedForThreadInterrupt_;
962 if (signalNumber) {
963 [[maybe_unused]] lock_guard critSec{sHandlerInstalled_};
964 if (sHandlerInstalled_) {
965 SignalHandlerRegistry::sThe.RemoveSignalHandler (SignalUsedForThreadInterrupt (), kCallInRepThreadAbortProcSignalHandler_);
966 sHandlerInstalled_ = false;
967 }
968 sSignalUsedForThreadInterrupt_ = signalNumber.value ();
969 // install new handler
970 if (not sHandlerInstalled_) {
971 SignalHandlerRegistry::sThe.AddSignalHandler (SignalUsedForThreadInterrupt (), kCallInRepThreadAbortProcSignalHandler_);
972 sHandlerInstalled_ = true;
973 }
974 }
975 return result;
976}
977#endif
978
979/*
980 ********************************************************************************
981 **************************** Thread::FormatThreadID ****************************
982 ********************************************************************************
983 */
984wstring Thread::FormatThreadID (Thread::IDType threadID, const FormatThreadInfo& formatThreadInfo)
985{
986 return String::FromNarrowSDKString (FormatThreadID_A (threadID, formatThreadInfo)).As<wstring> ();
987}
988
989string Thread::FormatThreadID_A (Thread::IDType threadID, const FormatThreadInfo& formatThreadInfo)
990{
992
993 /*
994 * stdc++ doesn't define a way to get the INT thread id, just a string. But they don't format it the
995 * way we usually format a thread ID (hex, fixed width). So do that, so thread IDs look more consistent.
996 */
997 stringstream out;
998 out << threadID;
999
1000#if qStroika_Platform_Windows
1001 constexpr size_t kSizeOfThreadID_ = sizeof (DWORD); // All MSFT SDK Thread APIs use DWORD for thread id
1002#elif qStroika_Platform_POSIX
1003 constexpr size_t kSizeOfThreadID_ = sizeof (pthread_t);
1004#else
1005 // on MSFT this object is much larger than thread id because it includes handle and id
1006 // Not a reliable measure anywhere, but probably our best guess
1007 constexpr size_t kSizeOfThreadID_ = sizeof (Thread::IDType);
1008#endif
1009
1010 if constexpr (kSizeOfThreadID_ >= sizeof (uint64_t)) {
1011 uint64_t threadIDInt = 0;
1012 out >> threadIDInt;
1013 return formatThreadInfo.fIncludeLeadingZeros ? Characters::CString::Format ("0x%016llx", threadIDInt)
1014 : Characters::CString::Format ("0x%llx", threadIDInt);
1015 }
1016 else {
1017 uint32_t threadIDInt = 0;
1018 out >> threadIDInt;
1019 /*
1020 * Often, it appears ThreadIDs IDs are < 16bits, so making the printout format shorter makes it a bit more readable.
1021 *
1022 * However, I don't see any reliable way to tell this is the case, so don't bother for now. A trouble with checking on
1023 * a per-thread-id basis is that often the MAIN THREAD is 0, which is < 0xffff. Then we get one size and then
1024 * on the rest a different size, so the layout in the debug trace log looks funny.
1025 */
1026 constexpr bool kUse16BitThreadIDsIfTheyFit_{false};
1027 const bool kUse16Bit_ = kUse16BitThreadIDsIfTheyFit_ and threadIDInt <= 0xffff;
1028 if (kUse16Bit_) {
1029 return formatThreadInfo.fIncludeLeadingZeros ? Characters::CString::Format ("0x%04x", threadIDInt)
1030 : Characters::CString::Format ("0x%x", threadIDInt);
1031 }
1032 else {
1033 return formatThreadInfo.fIncludeLeadingZeros ? Characters::CString::Format ("0x%08x", threadIDInt)
1034 : Characters::CString::Format ("0x%x", threadIDInt);
1035 }
1036 }
1037}
1038
1039#if defined(__cpp_lib_jthread)
1040/*
1041 ********************************************************************************
1042 ************************ Thread::GetCurrentThreadStopToken *********************
1043 ********************************************************************************
1044 */
1045optional<stop_token> Thread::GetCurrentThreadStopToken ()
1046{
1047 if (Ptr curThread = GetCurrent ()) [[likely]] {
1048 return curThread.GetStopToken ();
1049 }
1050 else {
1051 return nullopt;
1052 }
1053}
1054#endif
1055
1056/*
1057 ********************************************************************************
1058 ******************* Thread::IsCurrentThreadInterruptible ***********************
1059 ********************************************************************************
1060 */
1062{
1063 return GetCurrent () != nullptr;
1064}
1065
1066/*
1067 ********************************************************************************
1068 *************************** Thread::CheckForInterruption ***********************
1069 ********************************************************************************
1070 */
1072{
1073 /*
1074 * NOTE: subtle but important that we use static Thread::InterruptException::kThe so we avoid
1075 * re-throw with string operations. Otherwise we would have to use SuppressInterruptionInContext
1076 * just before the actual throw.
1077 */
1078 if (shared_ptr<Ptr::Rep_> thisRunningThreadRep =
1079#if qCompilerAndStdLib_thread_local_static_inline_twice_Buggy
1080 Ptr::sCurrentThreadRep_BWA_ ().lock ()
1081#else
1082 Ptr::sCurrentThreadRep_.lock ()
1083#endif
1084 ) {
1085 if (t_InterruptionSuppressDepth_ == 0) [[likely]] {
1086 if (thisRunningThreadRep->fAbortRequested_) [[unlikely]] {
1087 // helpful to see threadAbort caused by Thread::CheckForInterruption in log
1088 Debug::TraceContextBumper ctx{"Thread::CheckForInterruption", "insideAbortLogic=true, thisThreadID={}"_f, GetCurrentThreadID ()};
1089 Throw (Thread::AbortException::kThe);
1090 }
1091 }
1092#if qStroika_Foundation_Debug_DefaultTracingOn
1093 else if (thisRunningThreadRep->fAbortRequested_) {
1094 static atomic<unsigned int> sSuperSuppress_{};
1095 if (++sSuperSuppress_ <= 1) {
1096 IgnoreExceptionsForCall (
1097 DbgTrace ("Suppressed interrupt throw: t_InterruptionSuppressDepth_={}, t_Interrupting_={}, backtrace: {}"_f,
1098 t_InterruptionSuppressDepth_, thisRunningThreadRep->fAbortRequested_.load (), Debug::BackTrace::Capture ()));
1099 sSuperSuppress_--;
1100 }
1101 }
1102#endif
1103 }
1104}
1105
1106/*
1107 ********************************************************************************
1108 ********************************** Thread::Yield *******************************
1109 ********************************************************************************
1110 */
1112{
1113 /*
1114 * Check before so we abort more quickly, and after since while we were sleeping we could be interrupted.
1115 * And this (yield) happens at a non-time critical point, so though checking before and after is redundant,
1116 * not importantly
1117 */
1119 this_thread::yield ();
1121}
#define RequireNotReached()
Definition Assertions.h:388
#define qStroika_Foundation_Debug_AssertionsChecked
The qStroika_Foundation_Debug_AssertionsChecked flag determines if assertions are checked and validat...
Definition Assertions.h:49
#define WeakAssertNotImplemented()
Definition Assertions.h:486
#define RequireNotNull(p)
Definition Assertions.h:350
#define AssertNotReached()
Definition Assertions.h:358
#define Verify(c)
Definition Assertions.h:422
time_point< RealtimeClock, DurationSeconds > TimePointSeconds
TimePointSeconds is a simpler approach to chrono::time_point, which doesn't require using templates e...
Definition Realtime.h:82
chrono::duration< double > DurationSeconds
chrono::duration<double> - a time span (length of time) measured in seconds, but high precision.
Definition Realtime.h:57
#define DbgTrace
Definition Trace.h:327
#define qStroika_Foundation_Debug_ShowThreadIndex
if true, emit a much shorter thread ID, making - I suspect (testing) for terser and clearer tracelogs...
Definition Trace.h:87
#define Stroika_Foundation_Debug_OptionalizeTraceArgs(...)
Definition Trace.h:288
Similar to String, but intended to more efficiently construct a String. Mutable type (String is large...
String is like std::u32string, except it is much easier to use, often much more space efficient,...
Definition String.h:201
nonvirtual string AsNarrowSDKString() const
Definition String.inl:832
static String FromNarrowSDKString(const char *from)
Definition String.inl:472
Set<T> is a container of T, where once an item is added, additionally adds () do nothing.
NOT a real mutex - just a debugging infrastructure support tool so in debug builds can be assured thr...
Exception<> is a replacement (subclass) for any std c++ exception class (e.g. the default 'std::excep...
Definition Exceptions.h:219
nonvirtual void AddSignalHandler(SignalID signal, const SignalHandler &handler)
nonvirtual void RemoveSignalHandler(SignalID signal, const SignalHandler &handler)
Wrap any object with Synchronized<> and it can be used similarly to the base type,...
Thread::Ptr is a (unsynchronized) smart pointer referencing an internally synchronized std::thread ob...
Definition Thread.h:357
nonvirtual void SetThreadName(const Characters::String &threadName) const
Definition Thread.cpp:627
nonvirtual void WaitForDoneUntil(Time::TimePointSeconds timeoutAt) const
Definition Thread.cpp:792
nonvirtual void Abort() const
Abort gracefully shuts down and terminates the given thread (using cooperative multitasking).
Definition Thread.cpp:726
nonvirtual bool WaitForDoneUntilQuietly(Time::TimePointSeconds timeoutAt) const
Definition Thread.cpp:800
nonvirtual void ThrowIfDoneWithException() const
Definition Thread.cpp:780
nonvirtual NativeHandleType GetNativeHandle() const noexcept
Definition Thread.inl:178
nonvirtual Characters::String ToString() const
Definition Thread.cpp:640
nonvirtual void AbortAndWaitForDoneUntil(Time::TimePointSeconds timeoutAt) const
Abort () the thread, and then WaitForDone ()
Definition Thread.cpp:765
nonvirtual Characters::String GetThreadName() const
Definition Thread.cpp:621
nonvirtual void SetThreadPriority(Priority priority=Priority::eNormal) const
Definition Thread.cpp:606
Iterable<T> is a base class for containers which easily produce an Iterator<T> to traverse them.
Definition Iterable.h:234
nonvirtual RESULT_CONTAINER Map(ELEMENT_MAPPER &&elementMapper) const
functional API which iterates over all members of an Iterable, applies a map function to each element...
nonvirtual void Apply(const function< void(ArgByValueType< T > item)> &doToElement) const
Run the argument function (or lambda) on each element of the container.
String ToString(T &&t, ARGS... args)
Return a debug-friendly, display version of the argument: not guaranteed parsable or usable except fo...
Definition ToString.inl:424
void WaitAndPumpMessages(HWND dialog=nullptr, Time::DurationSeconds forNSecs=0.1s)
Ptr New(const function< void()> &fun2CallOnce, const optional< Characters::String > &name, const optional< Configuration > &configuration)
Definition Thread.cpp:887
void AbortAndWaitForDoneUntil(const Traversal::Iterable< Ptr > &threads, Time::TimePointSeconds timeoutAt)
Definition Thread.cpp:927
thread::native_handle_type NativeHandleType
Definition Thread.h:245
void Start(const Traversal::Iterable< Ptr > &threads)
Definition Thread.inl:347
wstring FormatThreadID(Thread::IDType threadID, const FormatThreadInfo &formatInfo={})
Definition Thread.cpp:984
void WaitForDone(const Traversal::Iterable< Ptr > &threads, Time::DurationSeconds timeout=Time::kInfinity)
Definition Thread.inl:351
dont_inline void Yield()
calls CheckForInterruption, and std::this_thread::yield ()
Definition Thread.cpp:1111
Configuration DefaultConfiguration() noexcept
Definition Thread.cpp:897
void WaitForDoneUntil(const Traversal::Iterable< Ptr > &threads, Time::TimePointSeconds timeoutAt)
Definition Thread.cpp:940
void Abort(const Traversal::Iterable< Ptr > &threads)
foreach Thread t: t.Abort ()
Definition Thread.cpp:919
void AbortAndWaitForDone(const Traversal::Iterable< Ptr > &threads, Time::DurationSeconds timeout=Time::kInfinity)
shorthand for AbortAndWaitForDoneUntil (Time::GetTickCount () + timeout)
Definition Thread.inl:343
void Throw(T &&e2Throw)
like the builtin C++ 'throw', but stamps in the current Activity context and does helpful,...
Definition Throw.inl:54
auto Finally(FUNCTION &&f) -> Private_::FinallySentry< FUNCTION >
Definition Finally.inl:31
void ThrowError(error_code ec)
throw a SystemErrorException with the given error_code - or std::bad_alloc for errc::not_enough_memor...
errno_t SendSignal(thread::native_handle_type target, SignalID signal)
EXPERIMENTAL SUPPORT FOR THREAD STACK (and maybe other) settings.
Definition Thread.h:254