4#include "Stroika/Foundation/StroikaPreComp.h"
6#include "Stroika/Foundation/Common/StroikaConfig.h"
10#if qStroika_Foundation_Common_Platform_Windows
18#include "Stroika/Foundation/Containers/Set.h"
20#include "Stroika/Foundation/Debug/Main.h"
26#include "DLLSupport.h"
27#include "Exceptions.h"
29#include "TimeOutException.h"
31#if qStroika_Foundation_Common_Platform_POSIX
32#include "Platform/POSIX/SignalBlock.h"
33#include "SignalHandlers.h"
35#if qStroika_Foundation_Common_Platform_Windows
36#include "Platform/Windows/WaitSupport.h"
49using namespace Characters;
50using namespace Execution;
53 thread_local unsigned int t_InterruptionSuppressDepth_{0};
56#if qStroika_Foundation_Execution_Thread_SupportThreadStatistics
59 mutex sThreadSupportStatsMutex_;
60 set<Thread::IDType> sRunningThreads_;
62 struct AllThreadsDeadDetector_ {
63 AllThreadsDeadDetector_ ()
65 Require (sRunningThreads_.empty ());
67 ~AllThreadsDeadDetector_ ()
70 if (not sRunningThreads_.empty ()) {
71 DbgTrace (
"Threads {} running"_f, Thread::GetStatistics ().fRunningThreads);
72 Require (sRunningThreads_.empty ());
77 AllThreadsDeadDetector_ sAllThreadsDeadDetector_;
83#if qStroika_Foundation_Common_Platform_POSIX
89#if qStroika_Foundation_Common_Platform_POSIX
92SignalHandler kCallInRepThreadAbortProcSignalHandler_ = SIG_IGN;
100Thread::SuppressInterruptionInContext::SuppressInterruptionInContext ()
102 ++t_InterruptionSuppressDepth_;
105Thread::SuppressInterruptionInContext::~SuppressInterruptionInContext ()
107 Assert (t_InterruptionSuppressDepth_ >= 1);
108 t_InterruptionSuppressDepth_--;
124Thread::AbortException::AbortException ()
134Thread::IndexRegistrar::IndexRegistrar ()
136 Assert (not fInitialized_);
137 fInitialized_ =
true;
140Thread::IndexRegistrar::~IndexRegistrar ()
142 Assert (fInitialized_);
143 fInitialized_ =
false;
146unsigned int Thread::IndexRegistrar::GetIndex (
const IDType& threadID,
bool* wasNew)
148 if (not fInitialized_) {
149 if (wasNew !=
nullptr) {
154 [[maybe_unused]] lock_guard critSec{fMutex_};
155 auto i = fShownThreadIDs_.find (threadID);
156 unsigned int threadIndex2Show = 0;
157 if (i == fShownThreadIDs_.end ()) {
158 threadIndex2Show =
static_cast<unsigned int> (fShownThreadIDs_.size ());
159 fShownThreadIDs_.insert ({threadID, threadIndex2Show});
162 threadIndex2Show = i->second;
164 if (wasNew !=
nullptr) {
165 *wasNew = i == fShownThreadIDs_.end ();
167 return threadIndex2Show;
175Thread::Ptr::Rep_::Rep_ (
const function<
void ()>& runnable, [[maybe_unused]]
const optional<Configuration>& configuration)
176 : fRunnable_{runnable}
179#if qStroika_Foundation_Common_Platform_POSIX
180 static bool sDidInit_{
false};
183 kCallInRepThreadAbortProcSignalHandler_ =
SignalHandler{Rep_::InterruptionSignalHandler_, SignalHandler::Type::eDirect};
185#elif qStroika_Foundation_Common_Platform_Windows
186 if (configuration.has_value () and configuration->fThrowInterruptExceptionInsideUserAPC.has_value ()) {
187 fThrowInterruptExceptionInsideUserAPC_ = configuration->fThrowInterruptExceptionInsideUserAPC.value ();
192Thread::Ptr::Rep_::~Rep_ ()
208 if (fThreadValid_ and fThread_.joinable ()) {
213void Thread::Ptr::Rep_::Run_ ()
218 catch (
const AbortException&) {
224#if USE_NOISY_TRACE_IN_THIS_MODULE_
225 DbgTrace (
"in Thread::Ptr::Rep_::Run_ () - saving caught exception to repropagate later ({})"_f, current_exception ());
227 fSavedException_ = current_exception ();
233Stroika_Foundation_Debug_ATTRIBUTE_NO_SANITIZE_THREAD
Characters::String Thread::Ptr::Rep_::ToString ()
const
237 if (fRefCountBumpedInsideThreadMainEvent_.PeekIsSet ()) {
239 sb <<
"id: "sv << GetID ();
241 sb <<
", index: " << IndexRegistrar::sThe.GetIndex (GetID ());
244 if (not fThreadName_.empty ()) {
245 sb <<
", name: "sv << fThreadName_;
247 sb <<
", status: "sv << PeekStatusForToString_ ();
249 sb <<
", abortRequested: "sv << fAbortRequested_.load ();
250 sb <<
", refCountBumpedEvent: "sv << fRefCountBumpedInsideThreadMainEvent_.PeekIsSet ();
251 sb <<
", startReadyToTransitionToRunningEvent_: "sv << fStartReadyToTransitionToRunningEvent_.PeekIsSet ();
252 sb <<
", threadDoneAndCanJoin: "sv << fThreadDoneAndCanJoin_.PeekIsSet ();
253 if (fSavedException_.load () !=
nullptr) [[unlikely]] {
254 sb <<
", savedException: "sv << fSavedException_.load ();
256 if (fInitialPriority_.load () != nullopt) [[unlikely]] {
257 sb <<
", initialPriority: "sv << fInitialPriority_.load ();
259#if qStroika_Foundation_Common_Platform_Windows
260 sb <<
", throwInterruptExceptionInsideUserAPC: "sv << fThrowInterruptExceptionInsideUserAPC_;
266void Thread::Ptr::Rep_::ApplyThreadName2OSThreadObject ()
268 if (GetNativeHandle () != NativeHandleType{}) {
269#if qStroika_Foundation_Common_Platform_Windows
270 (void)::SetThreadDescription (GetNativeHandle (), fThreadName_.c_str ());
271#elif qStroika_Foundation_Common_Platform_POSIX && (__GLIBC__ > 2 or (__GLIBC__ == 2 and __GLIBC_MINOR__ >= 12))
275 constexpr size_t kMaxNameLen_{16 - 1};
277 if (narrowThreadName.length () > kMaxNameLen_) {
278 narrowThreadName.erase (kMaxNameLen_);
280 ::pthread_setname_np (GetNativeHandle (), narrowThreadName.c_str ());
285void Thread::Ptr::Rep_::ApplyPriority (Priority priority)
287#if USE_NOISY_TRACE_IN_THIS_MODULE_
289 "Thread::Ptr::Rep_::ApplyPriority",
"threads={}, priority={}"_f, Characters::ToString (*
this), Characters::ToString (priority))};
292 if (nh != NativeHandleType{}) {
293#if qStroika_Foundation_Common_Platform_Windows
295 case Priority::eLowest:
296 Verify (::SetThreadPriority (nh, THREAD_PRIORITY_LOWEST));
298 case Priority::eBelowNormal:
299 Verify (::SetThreadPriority (nh, THREAD_PRIORITY_BELOW_NORMAL));
301 case Priority::eNormal:
302 Verify (::SetThreadPriority (nh, THREAD_PRIORITY_NORMAL));
304 case Priority::eAboveNormal:
305 Verify (::SetThreadPriority (nh, THREAD_PRIORITY_ABOVE_NORMAL));
307 case Priority::eHighest:
308 Verify (::SetThreadPriority (nh, THREAD_PRIORITY_HIGHEST));
313#elif qStroika_Foundation_Common_Platform_POSIX
334 int schedulingPolicy{};
337 Verify (::pthread_getschedparam (nh, &schedulingPolicy, ¶m) == 0);
338 priorityMin = ::sched_get_priority_min (schedulingPolicy);
339 priorityMax = ::sched_get_priority_max (schedulingPolicy);
340#if USE_NOISY_TRACE_IN_THIS_MODULE_
341 DbgTrace (
"schedulingPolicy={}, default-priority={}, sPriorityMin_={}, priorityMax={}"_f, schedulingPolicy,
342 param.sched_priority, priorityMin, priorityMax);
345 int newPThreadPriority{priorityMin};
347 case Priority::eLowest:
348 newPThreadPriority = priorityMin;
350 case Priority::eBelowNormal:
351 newPThreadPriority = (priorityMax - priorityMin) * .25 + priorityMin;
353 case Priority::eNormal:
354 newPThreadPriority = (priorityMax - priorityMin) * .5 + priorityMin;
356 case Priority::eAboveNormal:
357 newPThreadPriority = (priorityMax - priorityMin) * .75 + priorityMin;
359 case Priority::eHighest:
360 newPThreadPriority = priorityMax;
364 newPThreadPriority = (priorityMax - priorityMin) * .5 + priorityMin;
366#if USE_NOISY_TRACE_IN_THIS_MODULE_
367 DbgTrace (
"Setting os thread priority for thread %{} to %{}"_f, (
long long int)(nh), newPThreadPriority);
374 sp.sched_priority = newPThreadPriority;
375 Verify (::pthread_setschedparam (nh, schedulingPolicy, &sp) == 0 or errno == EPERM);
383void Thread::Ptr::Rep_::ThreadMain_ (
const shared_ptr<Rep_> thisThreadRep)
noexcept
387 Characters::ToString (thisThreadRep))};
388#if qStroika_Foundation_Debug_AssertionsChecked
389 Require (Debug::AppearsDuringMainLifetime ());
390 [[maybe_unused]]
auto&& cleanupCheckMain =
Finally ([] ()
noexcept { Require (Debug::AppearsDuringMainLifetime ()); });
395 SuppressInterruptionInContext suppressInterruptionsOfThisThreadCallerKnowsWeHaveItBumpedAndCanProceed;
400 thisThreadRep->fRefCountBumpedInsideThreadMainEvent_.Set ();
404#if qCompilerAndStdLib_thread_local_static_inline_twice_Buggy
405 sCurrentThreadRep_BWA_ () = thisThreadRep;
407 sCurrentThreadRep_ = thisThreadRep;
410 [[maybe_unused]]
IDType thisThreadID = GetCurrentThreadID ();
412#if qStroika_Foundation_Execution_Thread_SupportThreadStatistics
414 Require (Debug::AppearsDuringMainLifetime ());
415 [[maybe_unused]] lock_guard critSec{sThreadSupportStatsMutex_};
416#if qStroika_Foundation_Debug_ShowThreadIndex
418 "Adding thread index {} to sRunningThreads_ ({})"_f, IndexRegistrar::sThe.GetIndex (thisThreadID),
421 DbgTrace (
"Adding thread id {} to sRunningThreads_ ({})"_f, thisThreadID, sRunningThreads_);
423 Verify (sRunningThreads_.insert (thisThreadID).second);
425 [[maybe_unused]]
auto&& cleanup =
Finally ([thisThreadID] ()
noexcept {
426 SuppressInterruptionInContext suppressThreadInterrupts;
427 Require (Debug::AppearsDuringMainLifetime ());
428 [[maybe_unused]] lock_guard critSec{sThreadSupportStatsMutex_};
429#if qStroika_Foundation_Debug_ShowThreadIndex
431 "removing thread index {} from sRunningThreads_ ({})"_f, IndexRegistrar::sThe.GetIndex (thisThreadID),
434 DbgTrace (
"removing thread id {} from sRunningThreads_ ({})"_f, thisThreadID, sRunningThreads_);
436 Verify (sRunningThreads_.erase (thisThreadID) == 1);
441#if qStroika_Foundation_Common_Platform_POSIX
446 sigemptyset (&mySet);
447 (void)sigaddset (&mySet, SignalUsedForThreadInterrupt ());
448 Verify (::pthread_sigmask (SIG_UNBLOCK, &mySet,
nullptr) == 0);
449#if USE_NOISY_TRACE_IN_THIS_MODULE_
450 DbgTrace (
"Just set SIG_UNBLOCK for signal {} in this thread"_f, SignalToName (SignalUsedForThreadInterrupt ()));
454 thisThreadRep->fStartReadyToTransitionToRunningEvent_.Wait ();
456 [[maybe_unused]]
auto&& cleanupThreadDoneEventSetter =
Finally ([thisThreadRep] ()
noexcept {
458 thisThreadRep->fThreadDoneAndCanJoin_.Set ();
461 Assert (thisThreadID == thisThreadRep->GetID ());
463 if (not thisThreadRep->fAbortRequested_ and not thisThreadRep->IsDone_ ()) {
464#if __cpp_lib_jthread >= 201911
468 stop_callback stopCallback{thisThreadRep->fStopToken_, [=] () {
470 if (thisThreadRep->fAbortRequested_) [[likely]] {
471 DbgTrace (
"skipped abort cuz done already"_f);
474 DbgTrace (
"Something triggered stop_token request stop, so doing abort to make sure we are in an aborting (flag) state."_f);
476 IgnoreExceptionsForCall (Ptr{thisThreadRep}.Abort ());
480 DbgTrace (
"In Thread::Rep_::ThreadMain_ - set state to RUNNING for thread: {}"_f, thisThreadRep->ToString ());
481 thisThreadRep->Run_ ();
482 DbgTrace (
"In Thread::Rep_::ThreadProc_ - setting state to COMPLETED for thread: {}"_f, thisThreadRep->ToString ());
485 catch (
const AbortException&) {
486 SuppressInterruptionInContext suppressCtx;
487 DbgTrace (
"In Thread::Rep_::ThreadProc_ - setting state to COMPLETED (InterruptException) for thread: {}"_f, thisThreadRep->ToString ());
488 thisThreadRep->fThreadDoneAndCanJoin_.Set ();
491 SuppressInterruptionInContext suppressCtx;
492 DbgTrace (
"In Thread::Rep_::ThreadProc_ - setting state to COMPLETED (due to EXCEPTION) for thread: {}"_f, thisThreadRep->ToString ());
493 thisThreadRep->fThreadDoneAndCanJoin_.Set ();
496 catch (
const AbortException&) {
497 DbgTrace (
"SERIOUS ERROR in Thread::Rep_::ThreadMain_ () - uncaught InterruptException - see sigsetmask stuff above - somehow not "
502 DbgTrace (
"SERIOUS ERROR in Thread::Rep_::ThreadMain_ () - uncaught exception"_f);
507void Thread::Ptr::Rep_::NotifyOfInterruptionFromAnyThread_ ()
517 Require (not IsDone_ ());
519 Require (fAbortRequested_);
523 if (GetCurrentThreadID () == GetID ()) [[unlikely]] {
537#if qStroika_Foundation_Common_Platform_POSIX
539 [[maybe_unused]] lock_guard critSec{sHandlerInstalled_};
540 if (not sHandlerInstalled_) {
542 sHandlerInstalled_ =
true;
545 (void)
SendSignal (GetNativeHandle (), SignalUsedForThreadInterrupt ());
546#elif qStroika_Foundation_Common_Platform_Windows
547 Verify (::QueueUserAPC (&CalledInRepThreadAbortProc_, GetNativeHandle (),
reinterpret_cast<ULONG_PTR
> (
this)));
552#if qStroika_Foundation_Common_Platform_POSIX
553void Thread::Ptr::Rep_::InterruptionSignalHandler_ (SignalID signal)
noexcept
566#elif qStroika_Foundation_Common_Platform_Windows
567void CALLBACK Thread::Ptr::Rep_::CalledInRepThreadAbortProc_ (ULONG_PTR lpParameter)
570 [[maybe_unused]] Ptr::Rep_* rep =
reinterpret_cast<Ptr::Rep_*
> (lpParameter);
571 Require (GetCurrentThreadID () == rep->GetID ());
572 if (rep->fThrowInterruptExceptionInsideUserAPC_) [[unlikely]] {
592 if (cfg->fStackSize) {
595 if (cfg->fStackGuard) {
598#if qStroika_Foundation_Common_Platform_Windows
599 if (cfg->fThrowInterruptExceptionInsideUserAPC) {
600 result.fThrowInterruptExceptionInsideUserAPC = *cfg->fThrowInterruptExceptionInsideUserAPC;
611 AssertExternallySynchronizedChecker::ReadContext declareContext{fThisAssertExternallySynchronized_};
615 fRep_->fInitialPriority_.store (priority);
619 fRep_->ApplyPriority (priority);
625 AssertExternallySynchronizedChecker::ReadContext declareContext{fThisAssertExternallySynchronized_};
626 return fRep_ ==
nullptr ?
String{} : fRep_->fThreadName_;
632 AssertExternallySynchronizedChecker::ReadContext declareContext{fThisAssertExternallySynchronized_};
633#if USE_NOISY_TRACE_IN_THIS_MODULE_
634 TraceContextBumper ctx{
"Thread::SetThreadName",
"thisThreadID={}, threadName = '{}'"_f, GetID (), threadName};
636 if (fRep_->fThreadName_ != threadName) {
637 fRep_->fThreadName_ = threadName.
As<wstring> ();
638 fRep_->ApplyThreadName2OSThreadObject ();
644 AssertExternallySynchronizedChecker::ReadContext declareContext{fThisAssertExternallySynchronized_};
645 return fRep_ ==
nullptr ?
"nullptr"sv : fRep_->ToString ();
650 AssertExternallySynchronizedChecker::ReadContext declareContext{fThisAssertExternallySynchronized_};
653 Require (not fRep_->fStartEverInitiated_);
654#if qStroika_Foundation_Debug_AssertionsChecked
656 auto s = GetStatus ();
657 Require (s == Status::eNotYetRunning or s == Status::eAborting);
686 fRep_->fStartEverInitiated_ =
true;
687 if (fRep_->fAbortRequested_) [[unlikely]] {
691#if __cpp_lib_jthread >= 201911
692 fRep_->fStopToken_ = fRep_->fStopSource_.get_token ();
693 fRep_->fThread_ = jthread{[
this] () ->
void { Rep_::ThreadMain_ (fRep_); }};
695 fRep_->fThread_ = thread{[
this] () ->
void { Rep_::ThreadMain_ (fRep_); }};
697 fRep_->fThreadValid_ =
true;
700 fRep_->fRefCountBumpedInsideThreadMainEvent_.Wait ();
706 fRep_->ApplyThreadName2OSThreadObject ();
707 if (optional<Priority> p = fRep_->fInitialPriority_.load ()) {
708 fRep_->ApplyPriority (*p);
711 fRep_->fStartReadyToTransitionToRunningEvent_.Set ();
716 for (
auto s = GetStatus (); s != Status::eNotYetRunning; s = GetStatus ()) {
720 this_thread::yield ();
722#if qStroika_Foundation_Debug_AssertionsChecked
723 auto s = GetStatus ();
724 Ensure (s == Status::eRunning or s == Status::eAborting or s == Status::eCompleted);
731 Require (*
this !=
nullptr);
732 AssertExternallySynchronizedChecker::ReadContext declareContext{fThisAssertExternallySynchronized_};
734#if __cpp_lib_jthread >= 201911
735 bool wasAborted = fRep_->fAbortRequested_;
738 fRep_->fAbortRequested_ =
true;
739 if (fRep_->fStartEverInitiated_) {
740#if __cpp_lib_jthread >= 201911
743 if (not wasAborted) [[likely]] {
744 DbgTrace (
"Transitioned state to aborting, so calling fThread_.get_stop_source ().request_stop ();"_f);
745 fRep_->fStopSource_.request_stop ();
756 fRep_->fThreadDoneAndCanJoin_.Set ();
758 if (not IsDone ()) [[likely]] {
760 fRep_->NotifyOfInterruptionFromAnyThread_ ();
762#if USE_NOISY_TRACE_IN_THIS_MODULE_
763 DbgTrace (
"leaving *this = {}"_f, *
this);
770 "*this={}, timeoutAt={}"_f,
ToString (), timeoutAt)};
772 AssertExternallySynchronizedChecker::ReadContext declareContext{fThisAssertExternallySynchronized_};
780#if USE_NOISY_TRACE_IN_THIS_MODULE_
783 AssertExternallySynchronizedChecker::ReadContext declareContext{fThisAssertExternallySynchronized_};
784 if (fRep_ and fRep_->IsDone_ () and fRep_->fSavedException_.load () !=
nullptr) {
786 ReThrow (fRep_->fSavedException_.load (),
"Rethrowing exception across threads");
793 if (not WaitForDoneUntilQuietly (timeoutAt)) {
800#if USE_NOISY_TRACE_IN_THIS_MODULE_
802 "*this={}, timeoutAt={}"_f,
ToString (), timeoutAt)};
804 Require (*
this !=
nullptr);
805 AssertExternallySynchronizedChecker::ReadContext declareContext{fThisAssertExternallySynchronized_};
807 if (fRep_->fThreadDoneAndCanJoin_.WaitUntilQuietly (timeoutAt) == WaitableEvent::WaitStatus::eTriggered) {
818 if (fRep_->fThreadValid_ and fRep_->fThread_.joinable ()) {
820 fRep_->fThread_.join ();
824 Assert (timeoutAt <= Time::GetTickCount ());
828#if qStroika_Foundation_Common_Platform_Windows
831 AssertExternallySynchronizedChecker::ReadContext declareContext{fThisAssertExternallySynchronized_};
832 Require (*
this !=
nullptr);
834 HANDLE thread = fRep_->GetNativeHandle ();
835 if (thread == INVALID_HANDLE_VALUE) {
840 while (GetStatus () != Status::eCompleted) {
842 if (time2Wait <= 0s) {
856Thread::CleanupPtr::~CleanupPtr ()
858 if (*
this !=
nullptr) {
859 SuppressInterruptionInContext suppressInterruption;
874Thread::Ptr Thread::New (
const function<
void ()>& fun2CallOnce,
const optional<Characters::String>& name,
const optional<Configuration>& configuration)
877 Ptr ptr =
Ptr{Memory::MakeSharedPtr<Ptr::Rep_> (fun2CallOnce, CombineCFGs_ (configuration))};
886 return sDefaultConfiguration_.load ();
891 auto result = sDefaultConfiguration_.load ();
892 if (newConfiguration) {
893 sDefaultConfiguration_.store (newConfiguration.value ());
898#if qStroika_Foundation_Execution_Thread_SupportThreadStatistics
899Thread::Statistics Thread::GetStatistics ()
901 [[maybe_unused]] lock_guard critSec{sThreadSupportStatsMutex_};
908#if USE_NOISY_TRACE_IN_THIS_MODULE_
916#if USE_NOISY_TRACE_IN_THIS_MODULE_
918 "threads={}, timeoutAt={}"_f, threads, timeoutAt)};
929#if USE_NOISY_TRACE_IN_THIS_MODULE_
938#if qStroika_Foundation_Common_Platform_POSIX
940 SignalID sSignalUsedForThreadInterrupt_ = SIGUSR2;
942SignalID Thread::SignalUsedForThreadInterrupt () noexcept
944 return sSignalUsedForThreadInterrupt_;
946SignalID Thread::SignalUsedForThreadInterrupt (optional<SignalID> signalNumber)
948 SignalID result = sSignalUsedForThreadInterrupt_;
950 [[maybe_unused]] lock_guard critSec{sHandlerInstalled_};
951 if (sHandlerInstalled_) {
953 sHandlerInstalled_ =
false;
955 sSignalUsedForThreadInterrupt_ = signalNumber.value ();
957 if (not sHandlerInstalled_) {
959 sHandlerInstalled_ =
true;
976string Thread::FormatThreadID_A (
Thread::IDType threadID,
const FormatThreadInfo& formatThreadInfo)
987#if qStroika_Foundation_Common_Platform_Windows
988 constexpr size_t kSizeOfThreadID_ =
sizeof (DWORD);
989#elif qStroika_Foundation_Common_Platform_POSIX
990 constexpr size_t kSizeOfThreadID_ =
sizeof (pthread_t);
997 if constexpr (kSizeOfThreadID_ >=
sizeof (uint64_t)) {
998 uint64_t threadIDInt = 0;
1000 return formatThreadInfo.fIncludeLeadingZeros ? Characters::CString::Format (
"0x%016llx", threadIDInt)
1001 : Characters::CString::Format (
"0x%llx", threadIDInt);
1004 uint32_t threadIDInt = 0;
1013 constexpr bool kUse16BitThreadIDsIfTheyFit_{
false};
1014 const bool kUse16Bit_ = kUse16BitThreadIDsIfTheyFit_ and threadIDInt <= 0xffff;
1016 return formatThreadInfo.fIncludeLeadingZeros ? Characters::CString::Format (
"0x%04x", threadIDInt)
1017 : Characters::CString::Format (
"0x%x", threadIDInt);
1020 return formatThreadInfo.fIncludeLeadingZeros ? Characters::CString::Format (
"0x%08x", threadIDInt)
1021 : Characters::CString::Format (
"0x%x", threadIDInt);
1026#if qCompilerAndStdLib_ThreadLocalInlineDupSymbol_Buggy
1027#if __cpp_lib_jthread >= 201911
1033optional<stop_token> Thread::GetCurrentThreadStopToken ()
1036 return curThread.GetStopToken ();
1045#if qCompilerAndStdLib_ThreadLocalInlineDupSymbol_Buggy
1069 if (shared_ptr<Ptr::Rep_> thisRunningThreadRep =
1070#
if qCompilerAndStdLib_thread_local_static_inline_twice_Buggy
1071 Ptr::sCurrentThreadRep_BWA_ ().lock ()
1073 Ptr::sCurrentThreadRep_.lock ()
1076 if (t_InterruptionSuppressDepth_ == 0) [[likely]] {
1077 if (thisRunningThreadRep->fAbortRequested_) [[unlikely]] {
1079 Debug::TraceContextBumper ctx{
"Thread::CheckForInterruption",
"insideAbortLogic=true, thisThreadID={}"_f, GetCurrentThreadID ()};
1080 Throw (Thread::AbortException::kThe);
1083#if qStroika_Foundation_Debug_DefaultTracingOn
1084 else if (thisRunningThreadRep->fAbortRequested_) {
1085 static atomic<unsigned int> sSuperSuppress_{};
1086 if (++sSuperSuppress_ <= 1) {
1087 IgnoreExceptionsForCall (
1088 DbgTrace (
"Suppressed interrupt throw: t_InterruptionSuppressDepth_={}, t_Interrupting_={}, backtrace: {}"_f,
1089 t_InterruptionSuppressDepth_, thisRunningThreadRep->fAbortRequested_.load (), Debug::BackTrace::Capture ()));
1110 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 () - but if doesn't finish fast enough, send extra aborts.
nonvirtual Characters::String GetThreadName() const
nonvirtual void SetThreadPriority(Priority priority=Priority::eNormal) const
static const TimeOutException kThe
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)
identical to builtin C++ 'throw' except that it does helpful, type dependent DbgTrace() messages firs...
auto Finally(FUNCTION &&f) -> Private_::FinallySentry< FUNCTION >
errno_t SendSignal(thread::native_handle_type target, SignalID signal)
EXPERIMENTAL SUPPORT FOR THREAD STACK (and maybe other) settings.
optional< size_t > fStackSize