4#include "Stroika/Foundation/StroikaPreComp.h"
6#include "Stroika/Foundation/Common/StroikaConfig.h"
10#if qStroika_Platform_Windows
18#include "Stroika/Foundation/Containers/Set.h"
20#include "Stroika/Foundation/Debug/Main.h"
25#include "Stroika/Foundation/Execution/Common.h"
26#include "Stroika/Foundation/Execution/DLLSupport.h"
27#include "Stroika/Foundation/Execution/Exceptions.h"
30#if qStroika_Platform_POSIX
31#include "Stroika/Foundation/Execution/Platform/POSIX/SignalBlock.h"
32#include "Stroika/Foundation/Execution/SignalHandlers.h"
34#if qStroika_Platform_Windows
35#include "Stroika/Foundation/Execution/Platform/Windows/WaitSupport.h"
48using namespace Characters;
49using namespace Execution;
52 thread_local unsigned int t_InterruptionSuppressDepth_{0};
55#if qStroika_Foundation_Execution_Thread_SupportThreadStatistics
58 mutex sThreadSupportStatsMutex_;
59 set<Thread::IDType> sRunningThreads_;
61 struct AllThreadsDeadDetector_ {
62 AllThreadsDeadDetector_ ()
64 Require (sRunningThreads_.empty ());
66 ~AllThreadsDeadDetector_ ()
69 if (not sRunningThreads_.empty ()) {
70 DbgTrace (
"Threads {} running"_f, Thread::GetStatistics ().fRunningThreads);
71 Require (sRunningThreads_.empty ());
76 AllThreadsDeadDetector_ sAllThreadsDeadDetector_;
82#if qStroika_Platform_POSIX
88#if qStroika_Platform_POSIX
91SignalHandler kCallInRepThreadAbortProcSignalHandler_ = SIG_IGN;
99Thread::SuppressInterruptionInContext::SuppressInterruptionInContext ()
101 ++t_InterruptionSuppressDepth_;
104Thread::SuppressInterruptionInContext::~SuppressInterruptionInContext ()
106 Assert (t_InterruptionSuppressDepth_ >= 1);
107 t_InterruptionSuppressDepth_--;
123Thread::AbortException::AbortException ()
133Thread::IndexRegistrar::IndexRegistrar ()
135 Assert (not fInitialized_);
136 fInitialized_ =
true;
139Thread::IndexRegistrar::~IndexRegistrar ()
141 Assert (fInitialized_);
142 fInitialized_ =
false;
145unsigned int Thread::IndexRegistrar::GetIndex (
const IDType& threadID,
bool* wasNew)
147 if (not fInitialized_) {
148 if (wasNew !=
nullptr) {
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});
161 threadIndex2Show = i->second;
163 if (wasNew !=
nullptr) {
164 *wasNew = i == fShownThreadIDs_.end ();
166 return threadIndex2Show;
174Thread::Ptr::Rep_::Rep_ (
const function<
void ()>& runnable, [[maybe_unused]]
const optional<Configuration>& configuration)
175 : fRunnable_{runnable}
178#if qStroika_Platform_POSIX
179 static bool sDidInit_{
false};
182 kCallInRepThreadAbortProcSignalHandler_ =
SignalHandler{Rep_::InterruptionSignalHandler_, SignalHandler::Type::eDirect};
184#elif qStroika_Platform_Windows
185 if (configuration.has_value () and configuration->fThrowInterruptExceptionInsideUserAPC.has_value ()) {
186 fThrowInterruptExceptionInsideUserAPC_ = configuration->fThrowInterruptExceptionInsideUserAPC.value ();
191Thread::Ptr::Rep_::~Rep_ ()
207 if (fThreadValid_ and fThread_.joinable ()) {
212void Thread::Ptr::Rep_::Run_ ()
217 catch (
const AbortException&) {
223#if USE_NOISY_TRACE_IN_THIS_MODULE_
224 DbgTrace (
"in Thread::Ptr::Rep_::Run_ () - saving caught exception to repropagate later ({})"_f, current_exception ());
226 fSavedException_ = current_exception ();
232Stroika_Foundation_Debug_ATTRIBUTE_NO_SANITIZE_THREAD
Characters::String Thread::Ptr::Rep_::ToString ()
const
236 if (fRefCountBumpedInsideThreadMainEvent_.PeekIsSet ()) {
238 sb <<
"id: "sv << GetID ();
240 sb <<
", index: " << IndexRegistrar::sThe.GetIndex (GetID ());
243 if (not fThreadName_.empty ()) {
244 sb <<
", name: "sv << fThreadName_;
246 sb <<
", status: "sv << PeekStatusForToString_ ();
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 ();
255 if (fInitialPriority_.load () != nullopt) [[unlikely]] {
256 sb <<
", initialPriority: "sv << fInitialPriority_.load ();
258#if qStroika_Platform_Windows
259 sb <<
", throwInterruptExceptionInsideUserAPC: "sv << fThrowInterruptExceptionInsideUserAPC_;
265void Thread::Ptr::Rep_::ApplyThreadName2OSThreadObject ()
267 if (GetNativeHandle () != NativeHandleType{}) {
268#if qStroika_Platform_Windows
269 (void)::SetThreadDescription (GetNativeHandle (), fThreadName_.c_str ());
270#elif qStroika_Platform_POSIX && (__GLIBC__ > 2 or (__GLIBC__ == 2 and __GLIBC_MINOR__ >= 12))
274 constexpr size_t kMaxNameLen_{16 - 1};
276 if (narrowThreadName.length () > kMaxNameLen_) {
277 narrowThreadName.erase (kMaxNameLen_);
279 ::pthread_setname_np (GetNativeHandle (), narrowThreadName.c_str ());
284void Thread::Ptr::Rep_::ApplyPriority (Priority priority)
286#if USE_NOISY_TRACE_IN_THIS_MODULE_
288 "Thread::Ptr::Rep_::ApplyPriority",
"threads={}, priority={}"_f, Characters::ToString (*
this), Characters::ToString (priority))};
291 if (nh != NativeHandleType{}) {
292#if qStroika_Platform_Windows
294 case Priority::eLowest:
295 Verify (::SetThreadPriority (nh, THREAD_PRIORITY_LOWEST));
297 case Priority::eBelowNormal:
298 Verify (::SetThreadPriority (nh, THREAD_PRIORITY_BELOW_NORMAL));
300 case Priority::eNormal:
301 Verify (::SetThreadPriority (nh, THREAD_PRIORITY_NORMAL));
303 case Priority::eAboveNormal:
304 Verify (::SetThreadPriority (nh, THREAD_PRIORITY_ABOVE_NORMAL));
306 case Priority::eHighest:
307 Verify (::SetThreadPriority (nh, THREAD_PRIORITY_HIGHEST));
312#elif qStroika_Platform_POSIX
333 int schedulingPolicy{};
336 Verify (::pthread_getschedparam (nh, &schedulingPolicy, ¶m) == 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);
344 int newPThreadPriority{priorityMin};
346 case Priority::eLowest:
347 newPThreadPriority = priorityMin;
349 case Priority::eBelowNormal:
350 newPThreadPriority = (priorityMax - priorityMin) * .25 + priorityMin;
352 case Priority::eNormal:
353 newPThreadPriority = (priorityMax - priorityMin) * .5 + priorityMin;
355 case Priority::eAboveNormal:
356 newPThreadPriority = (priorityMax - priorityMin) * .75 + priorityMin;
358 case Priority::eHighest:
359 newPThreadPriority = priorityMax;
363 newPThreadPriority = (priorityMax - priorityMin) * .5 + priorityMin;
365#if USE_NOISY_TRACE_IN_THIS_MODULE_
366 DbgTrace (
"Setting os thread priority for thread %{} to %{}"_f, (
long long int)(nh), newPThreadPriority);
373 sp.sched_priority = newPThreadPriority;
374 Verify (::pthread_setschedparam (nh, schedulingPolicy, &sp) == 0 or errno == EPERM);
382void Thread::Ptr::Rep_::ThreadMain_ (
const shared_ptr<Rep_> thisThreadRep)
noexcept
386 Characters::ToString (thisThreadRep))};
387#if qStroika_Foundation_Debug_AssertionsChecked
388 Require (Debug::AppearsDuringMainLifetime ());
389 [[maybe_unused]]
auto&& cleanupCheckMain =
Finally ([] ()
noexcept { Require (Debug::AppearsDuringMainLifetime ()); });
394 SuppressInterruptionInContext suppressInterruptionsOfThisThreadCallerKnowsWeHaveItBumpedAndCanProceed;
399 thisThreadRep->fRefCountBumpedInsideThreadMainEvent_.Set ();
403#if qCompilerAndStdLib_thread_local_static_inline_twice_Buggy
404 sCurrentThreadRep_BWA_ () = thisThreadRep;
406 sCurrentThreadRep_ = thisThreadRep;
409 [[maybe_unused]]
IDType thisThreadID = GetCurrentThreadID ();
411#if qStroika_Foundation_Execution_Thread_SupportThreadStatistics
413 Require (Debug::AppearsDuringMainLifetime ());
414 [[maybe_unused]] lock_guard critSec{sThreadSupportStatsMutex_};
415#if qStroika_Foundation_Debug_ShowThreadIndex
417 "Adding thread index {} to sRunningThreads_ ({})"_f, IndexRegistrar::sThe.GetIndex (thisThreadID),
420 DbgTrace (
"Adding thread id {} to sRunningThreads_ ({})"_f, thisThreadID, sRunningThreads_);
422 Verify (sRunningThreads_.insert (thisThreadID).second);
424 [[maybe_unused]]
auto&& cleanup =
Finally ([thisThreadID] ()
noexcept {
425 SuppressInterruptionInContext suppressThreadInterrupts;
426 Require (Debug::AppearsDuringMainLifetime ());
427 [[maybe_unused]] lock_guard critSec{sThreadSupportStatsMutex_};
428#if qStroika_Foundation_Debug_ShowThreadIndex
430 "removing thread index {} from sRunningThreads_ ({})"_f, IndexRegistrar::sThe.GetIndex (thisThreadID),
433 DbgTrace (
"removing thread id {} from sRunningThreads_ ({})"_f, thisThreadID, sRunningThreads_);
435 Verify (sRunningThreads_.erase (thisThreadID) == 1);
440#if qStroika_Platform_POSIX
445 sigemptyset (&mySet);
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 ()));
453 thisThreadRep->fStartReadyToTransitionToRunningEvent_.Wait ();
455 [[maybe_unused]]
auto&& cleanupThreadDoneEventSetter =
Finally ([thisThreadRep] ()
noexcept {
457 thisThreadRep->fThreadDoneAndCanJoin_.Set ();
460 Assert (thisThreadID == thisThreadRep->GetID ());
462 if (not thisThreadRep->fAbortRequested_ and not thisThreadRep->IsDone_ ()) {
463#if defined(__cpp_lib_jthread)
467 stop_callback stopCallback{thisThreadRep->fStopToken_, [=] () {
469 if (thisThreadRep->fAbortRequested_) [[likely]] {
470 DbgTrace (
"skipped abort cuz done already"_f);
473 DbgTrace (
"Something triggered stop_token request stop, so doing abort to make sure we are in an aborting (flag) state."_f);
475 IgnoreExceptionsForCall (Ptr{thisThreadRep}.Abort ());
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 ());
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 ();
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 ();
495 catch (
const AbortException&) {
496 DbgTrace (
"SERIOUS ERROR in Thread::Rep_::ThreadMain_ () - uncaught InterruptException - see sigsetmask stuff above - somehow not "
501 DbgTrace (
"SERIOUS ERROR in Thread::Rep_::ThreadMain_ () - uncaught exception"_f);
506void Thread::Ptr::Rep_::NotifyOfInterruptionFromAnyThread_ ()
514 Require (fAbortRequested_);
518 if (GetCurrentThreadID () == GetID ()) [[unlikely]] {
532#if qStroika_Platform_POSIX
534 [[maybe_unused]] lock_guard critSec{sHandlerInstalled_};
535 if (not sHandlerInstalled_) {
537 sHandlerInstalled_ =
true;
540 (void)
SendSignal (GetNativeHandle (), SignalUsedForThreadInterrupt ());
541#elif qStroika_Platform_Windows
542 if (not ::QueueUserAPC (&CalledInRepThreadAbortProc_, GetNativeHandle (),
reinterpret_cast<ULONG_PTR
> (
this))) [[unlikely]] {
550#if qStroika_Platform_POSIX
551void Thread::Ptr::Rep_::InterruptionSignalHandler_ (SignalID signal)
noexcept
564#elif qStroika_Platform_Windows
565void CALLBACK Thread::Ptr::Rep_::CalledInRepThreadAbortProc_ (ULONG_PTR lpParameter)
568 [[maybe_unused]] Ptr::Rep_* rep =
reinterpret_cast<Ptr::Rep_*
> (lpParameter);
569 Require (GetCurrentThreadID () == rep->GetID ());
570 if (rep->fThrowInterruptExceptionInsideUserAPC_) [[unlikely]] {
590 if (cfg->fStackSize) {
593 if (cfg->fStackGuard) {
596#if qStroika_Platform_Windows
597 if (cfg->fThrowInterruptExceptionInsideUserAPC) {
598 result.fThrowInterruptExceptionInsideUserAPC = *cfg->fThrowInterruptExceptionInsideUserAPC;
609 AssertExternallySynchronizedChecker::ReadContext declareContext{fThisAssertExternallySynchronized_};
613 fRep_->fInitialPriority_.store (priority);
617 fRep_->ApplyPriority (priority);
623 AssertExternallySynchronizedChecker::ReadContext declareContext{fThisAssertExternallySynchronized_};
624 return fRep_ ==
nullptr ?
String{} : fRep_->fThreadName_;
630 AssertExternallySynchronizedChecker::ReadContext declareContext{fThisAssertExternallySynchronized_};
631#if USE_NOISY_TRACE_IN_THIS_MODULE_
632 TraceContextBumper ctx{
"Thread::SetThreadName",
"thisThreadID={}, threadName = '{}'"_f, GetID (), threadName};
634 if (fRep_->fThreadName_ != threadName) {
635 fRep_->fThreadName_ = threadName.
As<wstring> ();
636 fRep_->ApplyThreadName2OSThreadObject ();
642 AssertExternallySynchronizedChecker::ReadContext declareContext{fThisAssertExternallySynchronized_};
643 return fRep_ ==
nullptr ?
"nullptr"sv : fRep_->ToString ();
648 AssertExternallySynchronizedChecker::ReadContext declareContext{fThisAssertExternallySynchronized_};
651 Require (not fRep_->fStartEverInitiated_);
652#if qStroika_Foundation_Debug_AssertionsChecked
654 auto s = GetStatus ();
655 Require (s == Status::eNotYetRunning or s == Status::eAborting);
684 fRep_->fStartEverInitiated_ =
true;
685 if (fRep_->fAbortRequested_) [[unlikely]] {
689#if defined(__cpp_lib_jthread)
690 fRep_->fStopToken_ = fRep_->fStopSource_.get_token ();
691 fRep_->fThread_ = jthread{[
this] () ->
void { Rep_::ThreadMain_ (fRep_); }};
693 fRep_->fThread_ = thread{[
this] () ->
void { Rep_::ThreadMain_ (fRep_); }};
695 fRep_->fThreadValid_ =
true;
698 fRep_->fRefCountBumpedInsideThreadMainEvent_.Wait ();
704 fRep_->ApplyThreadName2OSThreadObject ();
705 if (optional<Priority> p = fRep_->fInitialPriority_.load ()) {
706 fRep_->ApplyPriority (*p);
709 fRep_->fStartReadyToTransitionToRunningEvent_.Set ();
714 for (
auto s = GetStatus (); s != Status::eNotYetRunning; s = GetStatus ()) {
718 this_thread::yield ();
720#if qStroika_Foundation_Debug_AssertionsChecked
721 auto s = GetStatus ();
722 Ensure (s == Status::eRunning or s == Status::eAborting or s == Status::eCompleted);
729 Require (*
this !=
nullptr);
730 AssertExternallySynchronizedChecker::ReadContext declareContext{fThisAssertExternallySynchronized_};
732#if defined(__cpp_lib_jthread)
733 bool wasAborted = fRep_->fAbortRequested_;
736 fRep_->fAbortRequested_ =
true;
737 if (fRep_->fStartEverInitiated_) {
738#if defined(__cpp_lib_jthread)
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 ();
754 fRep_->fThreadDoneAndCanJoin_.Set ();
756 if (not IsDone ()) [[likely]] {
758 fRep_->NotifyOfInterruptionFromAnyThread_ ();
760#if USE_NOISY_TRACE_IN_THIS_MODULE_
761 DbgTrace (
"leaving *this = {}"_f, *
this);
768 "*this={}, timeoutAt={}"_f,
ToString (), timeoutAt)};
770 AssertExternallySynchronizedChecker::ReadContext declareContext{fThisAssertExternallySynchronized_};
782#if USE_NOISY_TRACE_IN_THIS_MODULE_
785 AssertExternallySynchronizedChecker::ReadContext declareContext{fThisAssertExternallySynchronized_};
786 if (fRep_ and fRep_->IsDone_ () and fRep_->fSavedException_.load () !=
nullptr) {
788 ReThrow (fRep_->fSavedException_.load (),
"Rethrowing exception across threads");
795 if (not WaitForDoneUntilQuietly (timeoutAt)) {
802#if USE_NOISY_TRACE_IN_THIS_MODULE_
804 "*this={}, timeoutAt={}"_f,
ToString (), timeoutAt)};
806 Require (*
this !=
nullptr);
807 AssertExternallySynchronizedChecker::ReadContext declareContext{fThisAssertExternallySynchronized_};
809 if (fRep_->fThreadDoneAndCanJoin_.WaitUntilQuietly (timeoutAt) == WaitableEvent::WaitStatus::eTriggered) {
820 if (fRep_->fThreadValid_ and fRep_->fThread_.joinable ()) {
822 fRep_->fThread_.join ();
826 Assert (timeoutAt <= Time::GetTickCount ());
830#if qStroika_Platform_Windows
833 AssertExternallySynchronizedChecker::ReadContext declareContext{fThisAssertExternallySynchronized_};
834 Require (*
this !=
nullptr);
836 HANDLE thread = fRep_->GetNativeHandle ();
837 if (thread == INVALID_HANDLE_VALUE) {
842 while (GetStatus () != Status::eCompleted) {
844 if (time2Wait <= 0s) {
858Thread::CleanupPtr::~CleanupPtr ()
871 if (*
this !=
nullptr) {
872 SuppressInterruptionInContext suppressInterruption;
887Thread::Ptr Thread::New (
const function<
void ()>& fun2CallOnce,
const optional<Characters::String>& name,
const optional<Configuration>& configuration)
890 Ptr ptr =
Ptr{Memory::MakeSharedPtr<Ptr::Rep_> (fun2CallOnce, CombineCFGs_ (configuration))};
899 return sDefaultConfiguration_.load ();
904 auto result = sDefaultConfiguration_.load ();
905 if (newConfiguration) {
906 sDefaultConfiguration_.store (newConfiguration.value ());
911#if qStroika_Foundation_Execution_Thread_SupportThreadStatistics
912Thread::Statistics Thread::GetStatistics ()
914 [[maybe_unused]] lock_guard critSec{sThreadSupportStatsMutex_};
921#if USE_NOISY_TRACE_IN_THIS_MODULE_
929#if USE_NOISY_TRACE_IN_THIS_MODULE_
931 "threads={}, timeoutAt={}"_f, threads, timeoutAt)};
942#if USE_NOISY_TRACE_IN_THIS_MODULE_
951#if qStroika_Platform_POSIX
953 SignalID sSignalUsedForThreadInterrupt_ = SIGUSR2;
955SignalID Thread::SignalUsedForThreadInterrupt () noexcept
957 return sSignalUsedForThreadInterrupt_;
959SignalID Thread::SignalUsedForThreadInterrupt (optional<SignalID> signalNumber)
961 SignalID result = sSignalUsedForThreadInterrupt_;
963 [[maybe_unused]] lock_guard critSec{sHandlerInstalled_};
964 if (sHandlerInstalled_) {
966 sHandlerInstalled_ =
false;
968 sSignalUsedForThreadInterrupt_ = signalNumber.value ();
970 if (not sHandlerInstalled_) {
972 sHandlerInstalled_ =
true;
989string Thread::FormatThreadID_A (
Thread::IDType threadID,
const FormatThreadInfo& formatThreadInfo)
1000#if qStroika_Platform_Windows
1001 constexpr size_t kSizeOfThreadID_ =
sizeof (DWORD);
1002#elif qStroika_Platform_POSIX
1003 constexpr size_t kSizeOfThreadID_ =
sizeof (pthread_t);
1010 if constexpr (kSizeOfThreadID_ >=
sizeof (uint64_t)) {
1011 uint64_t threadIDInt = 0;
1013 return formatThreadInfo.fIncludeLeadingZeros ? Characters::CString::Format (
"0x%016llx", threadIDInt)
1014 : Characters::CString::Format (
"0x%llx", threadIDInt);
1017 uint32_t threadIDInt = 0;
1026 constexpr bool kUse16BitThreadIDsIfTheyFit_{
false};
1027 const bool kUse16Bit_ = kUse16BitThreadIDsIfTheyFit_ and threadIDInt <= 0xffff;
1029 return formatThreadInfo.fIncludeLeadingZeros ? Characters::CString::Format (
"0x%04x", threadIDInt)
1030 : Characters::CString::Format (
"0x%x", threadIDInt);
1033 return formatThreadInfo.fIncludeLeadingZeros ? Characters::CString::Format (
"0x%08x", threadIDInt)
1034 : Characters::CString::Format (
"0x%x", threadIDInt);
1039#if defined(__cpp_lib_jthread)
1045optional<stop_token> Thread::GetCurrentThreadStopToken ()
1047 if (Ptr curThread =
GetCurrent ()) [[likely]] {
1048 return curThread.GetStopToken ();
1078 if (shared_ptr<Ptr::Rep_> thisRunningThreadRep =
1079#
if qCompilerAndStdLib_thread_local_static_inline_twice_Buggy
1080 Ptr::sCurrentThreadRep_BWA_ ().lock ()
1082 Ptr::sCurrentThreadRep_.lock ()
1085 if (t_InterruptionSuppressDepth_ == 0) [[likely]] {
1086 if (thisRunningThreadRep->fAbortRequested_) [[unlikely]] {
1088 Debug::TraceContextBumper ctx{
"Thread::CheckForInterruption",
"insideAbortLogic=true, thisThreadID={}"_f, GetCurrentThreadID ()};
1089 Throw (Thread::AbortException::kThe);
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 ()));
1119 this_thread::yield ();
#define RequireNotReached()
#define qStroika_Foundation_Debug_AssertionsChecked
The qStroika_Foundation_Debug_AssertionsChecked flag determines if assertions are checked and validat...
#define WeakAssertNotImplemented()
#define RequireNotNull(p)
#define AssertNotReached()
time_point< RealtimeClock, DurationSeconds > TimePointSeconds
TimePointSeconds is a simpler approach to chrono::time_point, which doesn't require using templates e...
chrono::duration< double > DurationSeconds
chrono::duration<double> - a time span (length of time) measured in seconds, but high precision.
#define qStroika_Foundation_Debug_ShowThreadIndex
if true, emit a much shorter thread ID, making - I suspect (testing) for terser and clearer tracelogs...
#define Stroika_Foundation_Debug_OptionalizeTraceArgs(...)
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,...
nonvirtual string AsNarrowSDKString() const
static String FromNarrowSDKString(const char *from)
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...
nonvirtual void AddSignalHandler(SignalID signal, const SignalHandler &handler)
nonvirtual void RemoveSignalHandler(SignalID signal, const SignalHandler &handler)
static SignalHandlerRegistry sThe
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...
nonvirtual void SetThreadName(const Characters::String &threadName) const
nonvirtual void WaitForDoneUntil(Time::TimePointSeconds timeoutAt) const
nonvirtual void Abort() const
Abort gracefully shuts down and terminates the given thread (using cooperative multitasking).
nonvirtual bool WaitForDoneUntilQuietly(Time::TimePointSeconds timeoutAt) const
nonvirtual void Start() const
nonvirtual void ThrowIfDoneWithException() const
nonvirtual NativeHandleType GetNativeHandle() const noexcept
nonvirtual Characters::String ToString() const
nonvirtual void AbortAndWaitForDoneUntil(Time::TimePointSeconds timeoutAt) const
Abort () the thread, and then WaitForDone ()
nonvirtual Characters::String GetThreadName() const
nonvirtual void SetThreadPriority(Priority priority=Priority::eNormal) const
Iterable<T> is a base class for containers which easily produce an Iterator<T> to traverse them.
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...
Ptr New(const function< void()> &fun2CallOnce, const optional< Characters::String > &name, const optional< Configuration > &configuration)
void CheckForInterruption()
void AbortAndWaitForDoneUntil(const Traversal::Iterable< Ptr > &threads, Time::TimePointSeconds timeoutAt)
bool IsCurrentThreadInterruptible()
thread::native_handle_type NativeHandleType
void Start(const Traversal::Iterable< Ptr > &threads)
wstring FormatThreadID(Thread::IDType threadID, const FormatThreadInfo &formatInfo={})
void WaitForDone(const Traversal::Iterable< Ptr > &threads, Time::DurationSeconds timeout=Time::kInfinity)
dont_inline void Yield()
calls CheckForInterruption, and std::this_thread::yield ()
Configuration DefaultConfiguration() noexcept
void WaitForDoneUntil(const Traversal::Iterable< Ptr > &threads, Time::TimePointSeconds timeoutAt)
void Abort(const Traversal::Iterable< Ptr > &threads)
foreach Thread t: t.Abort ()
void AbortAndWaitForDone(const Traversal::Iterable< Ptr > &threads, Time::DurationSeconds timeout=Time::kInfinity)
shorthand for AbortAndWaitForDoneUntil (Time::GetTickCount () + timeout)
void Throw(T &&e2Throw)
like the builtin C++ 'throw', but stamps in the current Activity context and does helpful,...
auto Finally(FUNCTION &&f) -> Private_::FinallySentry< FUNCTION >
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.
optional< size_t > fStackSize