4#include "Stroika/Foundation/StroikaPreComp.h"
6#include "Stroika/Foundation/Common/StroikaConfig.h"
10#if qStroika_Foundation_Common_Platform_Windows
19#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"
56#ifndef qSupportSetThreadNameDebuggerCall_
57#if qStroika_Foundation_Debug_AssertionsChecked && qStroika_Foundation_Common_Platform_Windows
58#define qSupportSetThreadNameDebuggerCall_ 1
61#ifndef qSupportSetThreadNameDebuggerCall_
62#if qStroika_Foundation_Common_Platform_POSIX
63#define qSupportSetThreadNameDebuggerCall_ 1
66#ifndef qSupportSetThreadNameDebuggerCall_
67#define qSupportSetThreadNameDebuggerCall_ 0
70using namespace Characters;
71using namespace Execution;
74 thread_local unsigned int t_InterruptionSuppressDepth_{0};
77#if qStroika_Foundation_Execution_Thread_SupportThreadStatistics
80 mutex sThreadSupportStatsMutex_;
81 set<Thread::IDType> sRunningThreads_;
83 struct AllThreadsDeadDetector_ {
84 AllThreadsDeadDetector_ ()
86 Require (sRunningThreads_.empty ());
88 ~AllThreadsDeadDetector_ ()
91 if (not sRunningThreads_.empty ()) {
92 DbgTrace (
"Threads {} running"_f, Thread::GetStatistics ().fRunningThreads);
93 Require (sRunningThreads_.empty ());
98 AllThreadsDeadDetector_ sAllThreadsDeadDetector_;
102#if qStroika_Foundation_Common_Platform_Windows
104#if (_WIN32_WINNT < 0x0502)
110 using NTSTATUS = LONG;
111#define STATUS_SUCCESS ((NTSTATUS)0x00000000)
112 using KPRIORITY = LONG;
113 struct THREAD_BASIC_INFORMATION {
115 PVOID TebBaseAddress;
117 KAFFINITY AffinityMask;
119 KPRIORITY BasePriority;
121 enum THREAD_INFORMATION_CLASS {
122 ThreadBasicInformation = 0,
124 using pfnNtQueryInformationThread = NTSTATUS (__stdcall*) (HANDLE, THREAD_INFORMATION_CLASS, PVOID, ULONG, PULONG);
127 DWORD MyGetThreadId_ (HANDLE thread)
129#if (_WIN32_WINNT >= 0x0502)
130 return ::GetThreadId (thread);
134 using namespace XXX_;
135 static DLLLoader ntdll (SDKSTR (
"ntdll.dll"));
136 static pfnNtQueryInformationThread NtQueryInformationThread =
137 (pfnNtQueryInformationThread)ntdll.GetProcAddress (
"NtQueryInformationThread");
138 if (NtQueryInformationThread ==
nullptr)
140 THREAD_BASIC_INFORMATION tbi{};
141 THREAD_INFORMATION_CLASS tic = ThreadBasicInformation;
142 if (::NtQueryInformationThread (thread, tic, &tbi,
sizeof (tbi),
nullptr) != STATUS_SUCCESS) {
145 return tbi.ClientId.UniqueThread;
153#if qStroika_Foundation_Common_Platform_POSIX
159#if qStroika_Foundation_Common_Platform_POSIX
162SignalHandler kCallInRepThreadAbortProcSignalHandler_ = SIG_IGN;
170Thread::SuppressInterruptionInContext::SuppressInterruptionInContext ()
172 ++t_InterruptionSuppressDepth_;
175Thread::SuppressInterruptionInContext::~SuppressInterruptionInContext ()
177 Assert (t_InterruptionSuppressDepth_ >= 1);
178 t_InterruptionSuppressDepth_--;
194Thread::AbortException::AbortException ()
204Thread::IndexRegistrar::IndexRegistrar ()
206 Assert (not fInitialized_);
207 fInitialized_ =
true;
210Thread::IndexRegistrar::~IndexRegistrar ()
212 Assert (fInitialized_);
213 fInitialized_ =
false;
216unsigned int Thread::IndexRegistrar::GetIndex (
const IDType& threadID,
bool* wasNew)
218 if (not fInitialized_) {
219 if (wasNew !=
nullptr) {
224 [[maybe_unused]] lock_guard critSec{fMutex_};
225 auto i = fShownThreadIDs_.find (threadID);
226 unsigned int threadIndex2Show = 0;
227 if (i == fShownThreadIDs_.end ()) {
228 threadIndex2Show =
static_cast<unsigned int> (fShownThreadIDs_.size ());
229 fShownThreadIDs_.insert ({threadID, threadIndex2Show});
232 threadIndex2Show = i->second;
234 if (wasNew !=
nullptr) {
235 *wasNew = i == fShownThreadIDs_.end ();
237 return threadIndex2Show;
245Thread::Ptr::Rep_::Rep_ (
const function<
void ()>& runnable, [[maybe_unused]]
const optional<Configuration>& configuration)
246 : fRunnable_{runnable}
249#if qStroika_Foundation_Common_Platform_POSIX
250 static bool sDidInit_{
false};
253 kCallInRepThreadAbortProcSignalHandler_ =
SignalHandler{Rep_::InterruptionSignalHandler_, SignalHandler::Type::eDirect};
255#elif qStroika_Foundation_Common_Platform_Windows
256 if (configuration.has_value () and configuration->fThrowInterruptExceptionInsideUserAPC.has_value ()) {
257 fThrowInterruptExceptionInsideUserAPC_ = configuration->fThrowInterruptExceptionInsideUserAPC.value ();
262Thread::Ptr::Rep_::~Rep_ ()
278 if (fThreadValid_ and fThread_.joinable ()) {
283void Thread::Ptr::Rep_::Run_ ()
288 catch (
const AbortException&) {
294#if USE_NOISY_TRACE_IN_THIS_MODULE_
295 DbgTrace (
"in Thread::Ptr::Rep_::Run_ () - saving caught exception to repropagate later ({})"_f, current_exception ());
297 fSavedException_ = current_exception ();
303Stroika_Foundation_Debug_ATTRIBUTE_NO_SANITIZE_THREAD
Characters::String Thread::Ptr::Rep_::ToString ()
const
307 if (fRefCountBumpedInsideThreadMainEvent_.PeekIsSet ()) {
309 sb <<
"id: "sv << GetID ();
311 sb <<
", index: " << IndexRegistrar::sThe.GetIndex (GetID ());
314 if (not fThreadName_.empty ()) {
315 sb <<
", name: "sv << fThreadName_;
317 sb <<
", status: "sv << PeekStatusForToString_ ();
319 sb <<
", abortRequested: "sv << fAbortRequested_.load ();
320 sb <<
", refCountBumpedEvent: "sv << fRefCountBumpedInsideThreadMainEvent_.PeekIsSet ();
321 sb <<
", startReadyToTransitionToRunningEvent_: "sv << fStartReadyToTransitionToRunningEvent_.PeekIsSet ();
322 sb <<
", threadDoneAndCanJoin: "sv << fThreadDoneAndCanJoin_.PeekIsSet ();
323 if (fSavedException_.load () !=
nullptr) [[unlikely]] {
324 sb <<
", savedException: "sv << fSavedException_.load ();
326 if (fInitialPriority_.load () != nullopt) [[unlikely]] {
327 sb <<
", initialPriority: "sv << fInitialPriority_.load ();
329#if qStroika_Foundation_Common_Platform_Windows
330 sb <<
", throwInterruptExceptionInsideUserAPC: "sv << fThrowInterruptExceptionInsideUserAPC_;
336void Thread::Ptr::Rep_::ApplyThreadName2OSThreadObject ()
338 if (GetNativeHandle () != NativeHandleType{}) {
339#if qSupportSetThreadNameDebuggerCall_
340#if qStroika_Foundation_Common_Platform_Windows
341 if (::IsDebuggerPresent ()) {
343 struct THREADNAME_INFO {
350 THREADNAME_INFO info;
352 info.dwType = 0x1000;
353 info.szName = useThreadName.c_str ();
354 info.dwThreadID = MyGetThreadId_ (GetNativeHandle ());
357 IgnoreExceptionsForCall (::RaiseException (0x406D1388, 0,
sizeof (info) /
sizeof (DWORD), (ULONG_PTR*)&info));
359#elif qStroika_Foundation_Common_Platform_POSIX && (__GLIBC__ > 2 or (__GLIBC__ == 2 and __GLIBC_MINOR__ >= 12))
363 constexpr size_t kMaxNameLen_{16 - 1};
365 if (narrowThreadName.length () > kMaxNameLen_) {
366 narrowThreadName.erase (kMaxNameLen_);
368 ::pthread_setname_np (GetNativeHandle (), narrowThreadName.c_str ());
374void Thread::Ptr::Rep_::ApplyPriority (Priority priority)
376#if USE_NOISY_TRACE_IN_THIS_MODULE_
378 "Thread::Ptr::Rep_::ApplyPriority",
"threads={}, priority={}"_f, Characters::ToString (*
this), Characters::ToString (priority))};
381 if (nh != NativeHandleType{}) {
382#if qStroika_Foundation_Common_Platform_Windows
384 case Priority::eLowest:
385 Verify (::SetThreadPriority (nh, THREAD_PRIORITY_LOWEST));
387 case Priority::eBelowNormal:
388 Verify (::SetThreadPriority (nh, THREAD_PRIORITY_BELOW_NORMAL));
390 case Priority::eNormal:
391 Verify (::SetThreadPriority (nh, THREAD_PRIORITY_NORMAL));
393 case Priority::eAboveNormal:
394 Verify (::SetThreadPriority (nh, THREAD_PRIORITY_ABOVE_NORMAL));
396 case Priority::eHighest:
397 Verify (::SetThreadPriority (nh, THREAD_PRIORITY_HIGHEST));
402#elif qStroika_Foundation_Common_Platform_POSIX
423 int schedulingPolicy{};
426 Verify (::pthread_getschedparam (nh, &schedulingPolicy, ¶m) == 0);
427 priorityMin = ::sched_get_priority_min (schedulingPolicy);
428 priorityMax = ::sched_get_priority_max (schedulingPolicy);
429#if USE_NOISY_TRACE_IN_THIS_MODULE_
430 DbgTrace (
"schedulingPolicy={}, default-priority={}, sPriorityMin_={}, priorityMax={}"_f, schedulingPolicy,
431 param.sched_priority, priorityMin, priorityMax);
434 int newPThreadPriority{priorityMin};
436 case Priority::eLowest:
437 newPThreadPriority = priorityMin;
439 case Priority::eBelowNormal:
440 newPThreadPriority = (priorityMax - priorityMin) * .25 + priorityMin;
442 case Priority::eNormal:
443 newPThreadPriority = (priorityMax - priorityMin) * .5 + priorityMin;
445 case Priority::eAboveNormal:
446 newPThreadPriority = (priorityMax - priorityMin) * .75 + priorityMin;
448 case Priority::eHighest:
449 newPThreadPriority = priorityMax;
453 newPThreadPriority = (priorityMax - priorityMin) * .5 + priorityMin;
455#if USE_NOISY_TRACE_IN_THIS_MODULE_
456 DbgTrace (
"Setting os thread priority for thread %{} to %{}"_f, (
long long int)(nh), newPThreadPriority);
463 sp.sched_priority = newPThreadPriority;
464 Verify (::pthread_setschedparam (nh, schedulingPolicy, &sp) == 0 or errno == EPERM);
472void Thread::Ptr::Rep_::ThreadMain_ (
const shared_ptr<Rep_> thisThreadRep)
noexcept
476 Characters::ToString (thisThreadRep))};
477#if qStroika_Foundation_Debug_AssertionsChecked
478 Require (Debug::AppearsDuringMainLifetime ());
479 [[maybe_unused]]
auto&& cleanupCheckMain =
Finally ([] ()
noexcept { Require (Debug::AppearsDuringMainLifetime ()); });
484 SuppressInterruptionInContext suppressInterruptionsOfThisThreadCallerKnowsWeHaveItBumpedAndCanProceed;
489 thisThreadRep->fRefCountBumpedInsideThreadMainEvent_.Set ();
493#if qCompilerAndStdLib_thread_local_static_inline_twice_Buggy
494 sCurrentThreadRep_BWA_ () = thisThreadRep;
496 sCurrentThreadRep_ = thisThreadRep;
499 [[maybe_unused]]
IDType thisThreadID = GetCurrentThreadID ();
501#if qStroika_Foundation_Execution_Thread_SupportThreadStatistics
503 Require (Debug::AppearsDuringMainLifetime ());
504 [[maybe_unused]] lock_guard critSec{sThreadSupportStatsMutex_};
505#if qStroika_Foundation_Debug_ShowThreadIndex
507 "Adding thread index {} to sRunningThreads_ ({})"_f, IndexRegistrar::sThe.GetIndex (thisThreadID),
510 DbgTrace (
"Adding thread id {} to sRunningThreads_ ({})"_f, thisThreadID, sRunningThreads_);
512 Verify (sRunningThreads_.insert (thisThreadID).second);
514 [[maybe_unused]]
auto&& cleanup =
Finally ([thisThreadID] ()
noexcept {
515 SuppressInterruptionInContext suppressThreadInterrupts;
516 Require (Debug::AppearsDuringMainLifetime ());
517 [[maybe_unused]] lock_guard critSec{sThreadSupportStatsMutex_};
518#if qStroika_Foundation_Debug_ShowThreadIndex
520 "removing thread index {} from sRunningThreads_ ({})"_f, IndexRegistrar::sThe.GetIndex (thisThreadID),
523 DbgTrace (
"removing thread id {} from sRunningThreads_ ({})"_f, thisThreadID, sRunningThreads_);
525 Verify (sRunningThreads_.erase (thisThreadID) == 1);
530#if qStroika_Foundation_Common_Platform_POSIX
535 sigemptyset (&mySet);
536 (void)sigaddset (&mySet, SignalUsedForThreadInterrupt ());
537 Verify (::pthread_sigmask (SIG_UNBLOCK, &mySet,
nullptr) == 0);
538#if USE_NOISY_TRACE_IN_THIS_MODULE_
539 DbgTrace (
"Just set SIG_UNBLOCK for signal {} in this thread"_f, SignalToName (SignalUsedForThreadInterrupt ()));
543 thisThreadRep->fStartReadyToTransitionToRunningEvent_.Wait ();
545 [[maybe_unused]]
auto&& cleanupThreadDoneEventSetter =
Finally ([thisThreadRep] ()
noexcept {
547 thisThreadRep->fThreadDoneAndCanJoin_.Set ();
550 Assert (thisThreadID == thisThreadRep->GetID ());
552 bool doRun = not thisThreadRep->fAbortRequested_ and not thisThreadRep->IsDone_ ();
554#if __cpp_lib_jthread >= 201911
558 stop_callback stopCallback{thisThreadRep->fStopToken_, [=] () {
560 DbgTrace (
"Something triggered stop_token request stop, so doing abort to make sure we are in an aborting (flag) state."_f);
562 if (not thisThreadRep->fAbortRequested_) [[unlikely]] {
563 IgnoreExceptionsForCall (Ptr{thisThreadRep}.Abort ());
569 DbgTrace (
"In Thread::Rep_::ThreadMain_ - set state to RUNNING for thread: {}"_f, thisThreadRep->ToString ());
570 thisThreadRep->Run_ ();
571 DbgTrace (
"In Thread::Rep_::ThreadProc_ - setting state to COMPLETED for thread: {}"_f, thisThreadRep->ToString ());
574 catch (
const AbortException&) {
575 SuppressInterruptionInContext suppressCtx;
576 DbgTrace (
"In Thread::Rep_::ThreadProc_ - setting state to COMPLETED (InterruptException) for thread: {}"_f, thisThreadRep->ToString ());
577 thisThreadRep->fThreadDoneAndCanJoin_.Set ();
580 SuppressInterruptionInContext suppressCtx;
581 DbgTrace (
"In Thread::Rep_::ThreadProc_ - setting state to COMPLETED (due to EXCEPTION) for thread: {}"_f, thisThreadRep->ToString ());
582 thisThreadRep->fThreadDoneAndCanJoin_.Set ();
585 catch (
const AbortException&) {
586 DbgTrace (
"SERIOUS ERROR in Thread::Rep_::ThreadMain_ () - uncaught InterruptException - see sigsetmask stuff above - somehow not "
591 DbgTrace (
"SERIOUS ERROR in Thread::Rep_::ThreadMain_ () - uncaught exception"_f);
596void Thread::Ptr::Rep_::NotifyOfInterruptionFromAnyThread_ ()
603 Require (not IsDone_ ());
605 Require (fAbortRequested_);
609 if (GetCurrentThreadID () == GetID ()) [[unlikely]] {
623#if qStroika_Foundation_Common_Platform_POSIX
625 [[maybe_unused]] lock_guard critSec{sHandlerInstalled_};
626 if (not sHandlerInstalled_) {
628 sHandlerInstalled_ =
true;
631 (void)
SendSignal (GetNativeHandle (), SignalUsedForThreadInterrupt ());
632#elif qStroika_Foundation_Common_Platform_Windows
633 Verify (::QueueUserAPC (&CalledInRepThreadAbortProc_, GetNativeHandle (),
reinterpret_cast<ULONG_PTR
> (
this)));
638#if qStroika_Foundation_Common_Platform_POSIX
639void Thread::Ptr::Rep_::InterruptionSignalHandler_ (SignalID signal)
noexcept
652#elif qStroika_Foundation_Common_Platform_Windows
653void CALLBACK Thread::Ptr::Rep_::CalledInRepThreadAbortProc_ (ULONG_PTR lpParameter)
656 [[maybe_unused]] Ptr::Rep_* rep =
reinterpret_cast<Ptr::Rep_*
> (lpParameter);
657 Require (GetCurrentThreadID () == rep->GetID ());
658 if (rep->fThrowInterruptExceptionInsideUserAPC_) [[unlikely]] {
678 if (cfg->fStackSize) {
681 if (cfg->fStackGuard) {
684#if qStroika_Foundation_Common_Platform_Windows
685 if (cfg->fThrowInterruptExceptionInsideUserAPC) {
686 result.fThrowInterruptExceptionInsideUserAPC = *cfg->fThrowInterruptExceptionInsideUserAPC;
697 AssertExternallySynchronizedMutex::ReadContext declareContext{fThisAssertExternallySynchronized_};
701 fRep_->fInitialPriority_.store (priority);
705 fRep_->ApplyPriority (priority);
711 AssertExternallySynchronizedMutex::ReadContext declareContext{fThisAssertExternallySynchronized_};
712 return fRep_ ==
nullptr ?
String{} : fRep_->fThreadName_;
718 AssertExternallySynchronizedMutex::ReadContext declareContext{fThisAssertExternallySynchronized_};
719#if USE_NOISY_TRACE_IN_THIS_MODULE_
720 TraceContextBumper ctx{
"Thread::SetThreadName",
"thisThreadID={}, threadName = '{}'"_f, GetID (), threadName};
722 if (fRep_->fThreadName_ != threadName) {
723 fRep_->fThreadName_ = threadName.
As<wstring> ();
724 fRep_->ApplyThreadName2OSThreadObject ();
730 AssertExternallySynchronizedMutex::ReadContext declareContext{fThisAssertExternallySynchronized_};
731 return fRep_ ==
nullptr ?
"nullptr"sv : fRep_->ToString ();
736 AssertExternallySynchronizedMutex::ReadContext declareContext{fThisAssertExternallySynchronized_};
739 Require (not fRep_->fStartEverInitiated_);
740#if qStroika_Foundation_Debug_AssertionsChecked
742 auto s = GetStatus ();
743 Require (s == Status::eNotYetRunning or s == Status::eAborting);
772 fRep_->fStartEverInitiated_ =
true;
773 if (fRep_->fAbortRequested_) [[unlikely]] {
777#if __cpp_lib_jthread >= 201911
778 fRep_->fStopToken_ = fRep_->fStopSource_.get_token ();
779 fRep_->fThread_ = jthread{[
this] () ->
void { Rep_::ThreadMain_ (fRep_); }};
781 fRep_->fThread_ = thread{[
this] () ->
void { Rep_::ThreadMain_ (fRep_); }};
783 fRep_->fThreadValid_ =
true;
786 fRep_->fRefCountBumpedInsideThreadMainEvent_.Wait ();
792 fRep_->ApplyThreadName2OSThreadObject ();
793 if (optional<Priority> p = fRep_->fInitialPriority_.load ()) {
794 fRep_->ApplyPriority (*p);
797 fRep_->fStartReadyToTransitionToRunningEvent_.Set ();
802 for (
auto s = GetStatus (); s != Status::eNotYetRunning; s = GetStatus ()) {
806 this_thread::yield ();
808#if qStroika_Foundation_Debug_AssertionsChecked
809 auto s = GetStatus ();
810 Ensure (s == Status::eRunning or s == Status::eAborting or s == Status::eCompleted);
817 Require (*
this !=
nullptr);
818 AssertExternallySynchronizedMutex::ReadContext declareContext{fThisAssertExternallySynchronized_};
820#if __cpp_lib_jthread >= 201911
821 bool wasAborted = fRep_->fAbortRequested_;
824 fRep_->fAbortRequested_ =
true;
825 if (fRep_->fStartEverInitiated_) {
826#if __cpp_lib_jthread >= 201911
829 if (not wasAborted) [[likely]] {
830 DbgTrace (
"Transitioned state to aborting, so calling fThread_.get_stop_source ().request_stop ();"_f);
831 fRep_->fStopSource_.request_stop ();
842 fRep_->fThreadDoneAndCanJoin_.Set ();
844 if (not IsDone ()) [[likely]] {
846 fRep_->NotifyOfInterruptionFromAnyThread_ ();
848#if USE_NOISY_TRACE_IN_THIS_MODULE_
849 DbgTrace (
"leaving *this = {}"_f, *
this);
856 "*this={}, timeoutAt={}"_f,
ToString (), timeoutAt)};
858 AssertExternallySynchronizedMutex::ReadContext declareContext{fThisAssertExternallySynchronized_};
866#if USE_NOISY_TRACE_IN_THIS_MODULE_
869 AssertExternallySynchronizedMutex::ReadContext declareContext{fThisAssertExternallySynchronized_};
870 if (fRep_ and fRep_->IsDone_ () and fRep_->fSavedException_.load () !=
nullptr) {
872 ReThrow (fRep_->fSavedException_.load (),
"Rethrowing exception across threads");
879 if (not WaitForDoneUntilQuietly (timeoutAt)) {
886#if USE_NOISY_TRACE_IN_THIS_MODULE_
888 "*this={}, timeoutAt={}"_f,
ToString (), timeoutAt)};
890 Require (*
this !=
nullptr);
891 AssertExternallySynchronizedMutex::ReadContext declareContext{fThisAssertExternallySynchronized_};
893 if (fRep_->fThreadDoneAndCanJoin_.WaitUntilQuietly (timeoutAt) == WaitableEvent::WaitStatus::eTriggered) {
904 if (fRep_->fThreadValid_ and fRep_->fThread_.joinable ()) {
906 fRep_->fThread_.join ();
910 Assert (timeoutAt <= Time::GetTickCount ());
914#if qStroika_Foundation_Common_Platform_Windows
917 AssertExternallySynchronizedMutex::ReadContext declareContext{fThisAssertExternallySynchronized_};
918 Require (*
this !=
nullptr);
920 HANDLE thread = fRep_->GetNativeHandle ();
921 if (thread == INVALID_HANDLE_VALUE) {
926 while (GetStatus () != Status::eCompleted) {
928 if (time2Wait <= 0s) {
942Thread::CleanupPtr::~CleanupPtr ()
944 if (*
this !=
nullptr) {
945 SuppressInterruptionInContext suppressInterruption;
960Thread::Ptr Thread::New (
const function<
void ()>& fun2CallOnce,
const optional<Characters::String>& name,
const optional<Configuration>& configuration)
963 Ptr ptr =
Ptr{Memory::MakeSharedPtr<Ptr::Rep_> (fun2CallOnce, CombineCFGs_ (configuration))};
972 return sDefaultConfiguration_.load ();
977 auto result = sDefaultConfiguration_.load ();
978 if (newConfiguration) {
979 sDefaultConfiguration_.store (newConfiguration.value ());
984#if qStroika_Foundation_Execution_Thread_SupportThreadStatistics
985Thread::Statistics Thread::GetStatistics ()
987 [[maybe_unused]] lock_guard critSec{sThreadSupportStatsMutex_};
994#if USE_NOISY_TRACE_IN_THIS_MODULE_
1002#if USE_NOISY_TRACE_IN_THIS_MODULE_
1004 "threads={}, timeoutAt={}"_f, threads, timeoutAt)};
1015#if USE_NOISY_TRACE_IN_THIS_MODULE_
1024#if qStroika_Foundation_Common_Platform_POSIX
1026 SignalID sSignalUsedForThreadInterrupt_ = SIGUSR2;
1028SignalID Thread::SignalUsedForThreadInterrupt () noexcept
1030 return sSignalUsedForThreadInterrupt_;
1032SignalID Thread::SignalUsedForThreadInterrupt (optional<SignalID> signalNumber)
1034 SignalID result = sSignalUsedForThreadInterrupt_;
1036 [[maybe_unused]] lock_guard critSec{sHandlerInstalled_};
1037 if (sHandlerInstalled_) {
1039 sHandlerInstalled_ =
false;
1041 sSignalUsedForThreadInterrupt_ = signalNumber.value ();
1043 if (not sHandlerInstalled_) {
1045 sHandlerInstalled_ =
true;
1062string Thread::FormatThreadID_A (
Thread::IDType threadID,
const FormatThreadInfo& formatThreadInfo)
1073#if qStroika_Foundation_Common_Platform_Windows
1074 constexpr size_t kSizeOfThreadID_ =
sizeof (DWORD);
1075#elif qStroika_Foundation_Common_Platform_POSIX
1076 constexpr size_t kSizeOfThreadID_ =
sizeof (pthread_t);
1083 if constexpr (kSizeOfThreadID_ >=
sizeof (uint64_t)) {
1084 uint64_t threadIDInt = 0;
1086 return formatThreadInfo.fIncludeLeadingZeros ? Characters::CString::Format (
"0x%016llx", threadIDInt)
1087 : Characters::CString::Format (
"0x%llx", threadIDInt);
1090 uint32_t threadIDInt = 0;
1099 constexpr bool kUse16BitThreadIDsIfTheyFit_{
false};
1100 const bool kUse16Bit_ = kUse16BitThreadIDsIfTheyFit_ and threadIDInt <= 0xffff;
1102 return formatThreadInfo.fIncludeLeadingZeros ? Characters::CString::Format (
"0x%04x", threadIDInt)
1103 : Characters::CString::Format (
"0x%x", threadIDInt);
1106 return formatThreadInfo.fIncludeLeadingZeros ? Characters::CString::Format (
"0x%08x", threadIDInt)
1107 : Characters::CString::Format (
"0x%x", threadIDInt);
1112#if qCompilerAndStdLib_ThreadLocalInlineDupSymbol_Buggy
1113#if __cpp_lib_jthread >= 201911
1119optional<stop_token> Thread::GetCurrentThreadStopToken ()
1122 return curThread.GetStopToken ();
1131#if qCompilerAndStdLib_ThreadLocalInlineDupSymbol_Buggy
1155 if (shared_ptr<Ptr::Rep_> thisRunningThreadRep =
1156#
if qCompilerAndStdLib_thread_local_static_inline_twice_Buggy
1157 Ptr::sCurrentThreadRep_BWA_ ().lock ()
1159 Ptr::sCurrentThreadRep_.lock ()
1162 if (t_InterruptionSuppressDepth_ == 0) [[likely]] {
1163 if (thisRunningThreadRep->fAbortRequested_) [[unlikely]] {
1164 Throw (Thread::AbortException::kThe);
1167#if qStroika_Foundation_Debug_DefaultTracingOn
1168 else if (thisRunningThreadRep->fAbortRequested_) {
1169 static atomic<unsigned int> sSuperSuppress_{};
1170 if (++sSuperSuppress_ <= 1) {
1171 IgnoreExceptionsForCall (
DbgTrace (
"Suppressed interrupt throw: t_InterruptionSuppressDepth_={}, t_Interrupting_={}"_f,
1172 t_InterruptionSuppressDepth_, thisRunningThreadRep->fAbortRequested_.load ()));
1193 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 void Apply(const function< void(ArgByValueType< T > item)> &doToElement, Execution::SequencePolicy seq=Execution::SequencePolicy::eDEFAULT) const
Run the argument function (or lambda) on each element of the container.
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...
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