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"
25#include "DLLSupport.h"
26#include "Exceptions.h"
28#include "TimeOutException.h"
30#if qStroika_Foundation_Common_Platform_POSIX
31#include "Platform/POSIX/SignalBlock.h"
32#include "SignalHandlers.h"
34#if qStroika_Foundation_Common_Platform_Windows
35#include "Platform/Windows/WaitSupport.h"
55#ifndef qSupportSetThreadNameDebuggerCall_
56#if qStroika_Foundation_Debug_AssertionsChecked && qStroika_Foundation_Common_Platform_Windows
57#define qSupportSetThreadNameDebuggerCall_ 1
60#ifndef qSupportSetThreadNameDebuggerCall_
61#if qStroika_Foundation_Common_Platform_POSIX
62#define qSupportSetThreadNameDebuggerCall_ 1
65#ifndef qSupportSetThreadNameDebuggerCall_
66#define qSupportSetThreadNameDebuggerCall_ 0
69using namespace Characters;
70using namespace Execution;
73 thread_local unsigned int t_InterruptionSuppressDepth_{0};
76#if qStroika_Foundation_Execution_Thread_SupportThreadStatistics
79 mutex sThreadSupportStatsMutex_;
80 set<Thread::IDType> sRunningThreads_;
82 struct AllThreadsDeadDetector_ {
83 AllThreadsDeadDetector_ ()
85 Require (sRunningThreads_.empty ());
87 ~AllThreadsDeadDetector_ ()
90 if (not sRunningThreads_.empty ()) {
91 DbgTrace (
"Threads {} running"_f, Thread::GetStatistics ().fRunningThreads);
92 Require (sRunningThreads_.empty ());
97 AllThreadsDeadDetector_ sAllThreadsDeadDetector_;
101#if qStroika_Foundation_Common_Platform_Windows
103#if (_WIN32_WINNT < 0x0502)
109 using NTSTATUS = LONG;
110#define STATUS_SUCCESS ((NTSTATUS)0x00000000)
111 using KPRIORITY = LONG;
112 struct THREAD_BASIC_INFORMATION {
114 PVOID TebBaseAddress;
116 KAFFINITY AffinityMask;
118 KPRIORITY BasePriority;
120 enum THREAD_INFORMATION_CLASS {
121 ThreadBasicInformation = 0,
123 using pfnNtQueryInformationThread = NTSTATUS (__stdcall*) (HANDLE, THREAD_INFORMATION_CLASS, PVOID, ULONG, PULONG);
126 DWORD MyGetThreadId_ (HANDLE thread)
128#if (_WIN32_WINNT >= 0x0502)
129 return ::GetThreadId (thread);
133 using namespace XXX_;
134 static DLLLoader ntdll (SDKSTR (
"ntdll.dll"));
135 static pfnNtQueryInformationThread NtQueryInformationThread =
136 (pfnNtQueryInformationThread)ntdll.GetProcAddress (
"NtQueryInformationThread");
137 if (NtQueryInformationThread ==
nullptr)
139 THREAD_BASIC_INFORMATION tbi{};
140 THREAD_INFORMATION_CLASS tic = ThreadBasicInformation;
141 if (::NtQueryInformationThread (thread, tic, &tbi,
sizeof (tbi),
nullptr) != STATUS_SUCCESS) {
144 return tbi.ClientId.UniqueThread;
152#if qStroika_Foundation_Common_Platform_POSIX
158#if qStroika_Foundation_Common_Platform_POSIX
161SignalHandler kCallInRepThreadAbortProcSignalHandler_ = SIG_IGN;
169Thread::SuppressInterruptionInContext::SuppressInterruptionInContext ()
171 ++t_InterruptionSuppressDepth_;
174Thread::SuppressInterruptionInContext::~SuppressInterruptionInContext ()
176 Assert (t_InterruptionSuppressDepth_ >= 1);
177 t_InterruptionSuppressDepth_--;
193Thread::AbortException::AbortException ()
203Thread::IndexRegistrar::IndexRegistrar ()
205 Assert (not fInitialized_);
206 fInitialized_ =
true;
209Thread::IndexRegistrar::~IndexRegistrar ()
211 Assert (fInitialized_);
212 fInitialized_ =
false;
215unsigned int Thread::IndexRegistrar::GetIndex (
const IDType& threadID,
bool* wasNew)
217 if (not fInitialized_) {
218 if (wasNew !=
nullptr) {
223 [[maybe_unused]] lock_guard critSec{fMutex_};
224 auto i = fShownThreadIDs_.find (threadID);
225 unsigned int threadIndex2Show = 0;
226 if (i == fShownThreadIDs_.end ()) {
227 threadIndex2Show =
static_cast<unsigned int> (fShownThreadIDs_.size ());
228 fShownThreadIDs_.insert ({threadID, threadIndex2Show});
231 threadIndex2Show = i->second;
233 if (wasNew !=
nullptr) {
234 *wasNew = i == fShownThreadIDs_.end ();
236 return threadIndex2Show;
244Thread::Ptr::Rep_::Rep_ (
const function<
void ()>& runnable, [[maybe_unused]]
const optional<Configuration>& configuration)
245 : fRunnable_{runnable}
248#if qStroika_Foundation_Common_Platform_POSIX
249 static bool sDidInit_{
false};
252 kCallInRepThreadAbortProcSignalHandler_ =
SignalHandler{Rep_::InterruptionSignalHandler_, SignalHandler::Type::eDirect};
254#elif qStroika_Foundation_Common_Platform_Windows
255 if (configuration.has_value () and configuration->fThrowInterruptExceptionInsideUserAPC.has_value ()) {
256 fThrowInterruptExceptionInsideUserAPC_ = configuration->fThrowInterruptExceptionInsideUserAPC.value ();
261Thread::Ptr::Rep_::~Rep_ ()
277 if (fThreadValid_ and fThread_.joinable ()) {
282void Thread::Ptr::Rep_::Run_ ()
287 catch (
const AbortException&) {
293#if USE_NOISY_TRACE_IN_THIS_MODULE_
294 DbgTrace (
"in ad::Ptr::Rep_::Run_ () - saving caught exception to repropagate later ({})"_f, current_exception ());
296 fSavedException_ = current_exception ();
302Stroika_Foundation_Debug_ATTRIBUTE_NO_SANITIZE_THREAD
Characters::String Thread::Ptr::Rep_::ToString ()
const
306 if (fRefCountBumpedInsideThreadMainEvent_.PeekIsSet ()) {
308 sb <<
"id: "sv << GetID ();
310 sb <<
", index: " << IndexRegistrar::sThe.GetIndex (GetID ());
313 if (not fThreadName_.empty ()) {
314 sb <<
", name: "sv << fThreadName_;
316 sb <<
", status: "sv << PeekStatusForToString_ ();
318 sb <<
", abortRequested: "sv << fAbortRequested_.load ();
319 sb <<
", refCountBumpedEvent: "sv << fRefCountBumpedInsideThreadMainEvent_.PeekIsSet ();
320 sb <<
", startReadyToTransitionToRunningEvent_: "sv << fStartReadyToTransitionToRunningEvent_.PeekIsSet ();
321 sb <<
", threadDoneAndCanJoin: "sv << fThreadDoneAndCanJoin_.PeekIsSet ();
322 if (fSavedException_.load () !=
nullptr) [[unlikely]] {
323 sb <<
", savedException: "sv << fSavedException_.load ();
325 if (fInitialPriority_.load () != nullopt) [[unlikely]] {
326 sb <<
", initialPriority: "sv << fInitialPriority_.load ();
328#if qStroika_Foundation_Common_Platform_Windows
329 sb <<
", throwInterruptExceptionInsideUserAPC: "sv << fThrowInterruptExceptionInsideUserAPC_;
335void Thread::Ptr::Rep_::ApplyThreadName2OSThreadObject ()
337 if (GetNativeHandle () != NativeHandleType{}) {
338#if qSupportSetThreadNameDebuggerCall_
339#if qStroika_Foundation_Common_Platform_Windows
340 if (::IsDebuggerPresent ()) {
342 struct THREADNAME_INFO {
349 THREADNAME_INFO info;
351 info.dwType = 0x1000;
352 info.szName = useThreadName.c_str ();
353 info.dwThreadID = MyGetThreadId_ (GetNativeHandle ());
356 IgnoreExceptionsForCall (::RaiseException (0x406D1388, 0,
sizeof (info) /
sizeof (DWORD), (ULONG_PTR*)&info));
358#elif qStroika_Foundation_Common_Platform_POSIX && (__GLIBC__ > 2 or (__GLIBC__ == 2 and __GLIBC_MINOR__ >= 12))
362 constexpr size_t kMaxNameLen_{16 - 1};
364 if (narrowThreadName.length () > kMaxNameLen_) {
365 narrowThreadName.erase (kMaxNameLen_);
367 ::pthread_setname_np (GetNativeHandle (), narrowThreadName.c_str ());
373void Thread::Ptr::Rep_::ApplyPriority (Priority priority)
375#if USE_NOISY_TRACE_IN_THIS_MODULE_
377 "Thread::Ptr::Rep_::ApplyPriority",
"threads={}, priority={}"_f, Characters::ToString (*
this), Characters::ToString (priority))};
380 if (nh != NativeHandleType{}) {
381#if qStroika_Foundation_Common_Platform_Windows
383 case Priority::eLowest:
384 Verify (::SetThreadPriority (nh, THREAD_PRIORITY_LOWEST));
386 case Priority::eBelowNormal:
387 Verify (::SetThreadPriority (nh, THREAD_PRIORITY_BELOW_NORMAL));
389 case Priority::eNormal:
390 Verify (::SetThreadPriority (nh, THREAD_PRIORITY_NORMAL));
392 case Priority::eAboveNormal:
393 Verify (::SetThreadPriority (nh, THREAD_PRIORITY_ABOVE_NORMAL));
395 case Priority::eHighest:
396 Verify (::SetThreadPriority (nh, THREAD_PRIORITY_HIGHEST));
401#elif qStroika_Foundation_Common_Platform_POSIX
422 int schedulingPolicy{};
425 Verify (::pthread_getschedparam (nh, &schedulingPolicy, ¶m) == 0);
426 priorityMin = ::sched_get_priority_min (schedulingPolicy);
427 priorityMax = ::sched_get_priority_max (schedulingPolicy);
428#if USE_NOISY_TRACE_IN_THIS_MODULE_
429 DbgTrace (
"schedulingPolicy={}, default-priority={}, sPriorityMin_={}, priorityMax={}"_f, schedulingPolicy,
430 param.sched_priority, priorityMin, priorityMax);
433 int newPThreadPriority{priorityMin};
435 case Priority::eLowest:
436 newPThreadPriority = priorityMin;
438 case Priority::eBelowNormal:
439 newPThreadPriority = (priorityMax - priorityMin) * .25 + priorityMin;
441 case Priority::eNormal:
442 newPThreadPriority = (priorityMax - priorityMin) * .5 + priorityMin;
444 case Priority::eAboveNormal:
445 newPThreadPriority = (priorityMax - priorityMin) * .75 + priorityMin;
447 case Priority::eHighest:
448 newPThreadPriority = priorityMax;
452 newPThreadPriority = (priorityMax - priorityMin) * .5 + priorityMin;
454#if USE_NOISY_TRACE_IN_THIS_MODULE_
455 DbgTrace (
"Setting os thread priority for thread %{} to %{}"_f, (
long long int)(nh), newPThreadPriority);
462 sp.sched_priority = newPThreadPriority;
463 Verify (::pthread_setschedparam (nh, schedulingPolicy, &sp) == 0 or errno == EPERM);
471void Thread::Ptr::Rep_::ThreadMain_ (
const shared_ptr<Rep_> thisThreadRep)
noexcept
475 Characters::ToString (thisThreadRep))};
476#if qStroika_Foundation_Debug_AssertionsChecked
477 Require (Debug::AppearsDuringMainLifetime ());
478 [[maybe_unused]]
auto&& cleanupCheckMain =
Finally ([] ()
noexcept { Require (Debug::AppearsDuringMainLifetime ()); });
483 SuppressInterruptionInContext suppressInterruptionsOfThisThreadCallerKnowsWeHaveItBumpedAndCanProceed;
488 thisThreadRep->fRefCountBumpedInsideThreadMainEvent_.Set ();
492#if qCompilerAndStdLib_thread_local_static_inline_twice_Buggy
493 sCurrentThreadRep_BWA_ () = thisThreadRep;
495 sCurrentThreadRep_ = thisThreadRep;
498 [[maybe_unused]]
IDType thisThreadID = GetCurrentThreadID ();
500#if qStroika_Foundation_Execution_Thread_SupportThreadStatistics
502 Require (Debug::AppearsDuringMainLifetime ());
503 [[maybe_unused]] lock_guard critSec{sThreadSupportStatsMutex_};
504#if qStroika_Foundation_Debug_ShowThreadIndex
506 "Adding thread index {} to sRunningThreads_ ({})"_f, IndexRegistrar::sThe.GetIndex (thisThreadID),
509 DbgTrace (
"Adding thread id {} to sRunningThreads_ ({})"_f, thisThreadID, sRunningThreads_);
511 Verify (sRunningThreads_.insert (thisThreadID).second);
513 [[maybe_unused]]
auto&& cleanup =
Finally ([thisThreadID] ()
noexcept {
514 SuppressInterruptionInContext suppressThreadInterrupts;
515 Require (Debug::AppearsDuringMainLifetime ());
516 [[maybe_unused]] lock_guard critSec{sThreadSupportStatsMutex_};
517#if qStroika_Foundation_Debug_ShowThreadIndex
519 "removing thread index {} from sRunningThreads_ ({})"_f, IndexRegistrar::sThe.GetIndex (thisThreadID),
522 DbgTrace (
"removing thread id {} from sRunningThreads_ ({})"_f, thisThreadID, sRunningThreads_);
524 Verify (sRunningThreads_.erase (thisThreadID) == 1);
529#if qStroika_Foundation_Common_Platform_POSIX
534 sigemptyset (&mySet);
535 (void)sigaddset (&mySet, SignalUsedForThreadInterrupt ());
536 Verify (::pthread_sigmask (SIG_UNBLOCK, &mySet,
nullptr) == 0);
537#if USE_NOISY_TRACE_IN_THIS_MODULE_
538 DbgTrace (
"Just set SIG_UNBLOCK for signal {} in this thread"_f, SignalToName (SignalUsedForThreadInterrupt ()));
542 thisThreadRep->fStartReadyToTransitionToRunningEvent_.Wait ();
544 [[maybe_unused]]
auto&& cleanupThreadDoneEventSetter =
Finally ([thisThreadRep] ()
noexcept {
546 thisThreadRep->fThreadDoneAndCanJoin_.Set ();
549 Assert (thisThreadID == thisThreadRep->GetID ());
551 bool doRun = not thisThreadRep->fAbortRequested_ and not thisThreadRep->IsDone_ ();
553#if __cpp_lib_jthread >= 201911
557 stop_callback stopCallback{thisThreadRep->fStopToken_, [=] () {
559 DbgTrace (
"Something triggered stop_token request stop, so doing abort to make sure we are in an aborting (flag) state."_f);
561 if (not thisThreadRep->fAbortRequested_) [[unlikely]] {
562 IgnoreExceptionsForCall (Ptr{thisThreadRep}.Abort ());
568 DbgTrace (
"In Thread::Rep_::ThreadMain_ - set state to RUNNING for thread: {}"_f, thisThreadRep->ToString ());
569 thisThreadRep->Run_ ();
570 DbgTrace (
"In Thread::Rep_::ThreadProc_ - setting state to COMPLETED for thread: {}"_f, thisThreadRep->ToString ());
573 catch (
const AbortException&) {
574 SuppressInterruptionInContext suppressCtx;
575 DbgTrace (
"In Thread::Rep_::ThreadProc_ - setting state to COMPLETED (InterruptException) for thread: {}"_f, thisThreadRep->ToString ());
576 thisThreadRep->fThreadDoneAndCanJoin_.Set ();
579 SuppressInterruptionInContext suppressCtx;
580 DbgTrace (
"In Thread::Rep_::ThreadProc_ - setting state to COMPLETED (due to EXCEPTION) for thread: {}"_f, thisThreadRep->ToString ());
581 thisThreadRep->fThreadDoneAndCanJoin_.Set ();
584 catch (
const AbortException&) {
585 DbgTrace (
"SERIOUS ERROR in Thread::Rep_::ThreadMain_ () - uncaught InterruptException - see sigsetmask stuff above - somehow not "
590 DbgTrace (
"SERIOUS ERROR in Thread::Rep_::ThreadMain_ () - uncaught exception"_f);
595void Thread::Ptr::Rep_::NotifyOfInterruptionFromAnyThread_ ()
597 Require (not IsDone_ ());
600 Require (fAbortRequested_);
604 if (GetCurrentThreadID () == GetID ()) [[unlikely]] {
618#if qStroika_Foundation_Common_Platform_POSIX
620 [[maybe_unused]] lock_guard critSec{sHandlerInstalled_};
621 if (not sHandlerInstalled_) {
623 sHandlerInstalled_ =
true;
626 (void)
SendSignal (GetNativeHandle (), SignalUsedForThreadInterrupt ());
627#elif qStroika_Foundation_Common_Platform_Windows
628 Verify (::QueueUserAPC (&CalledInRepThreadAbortProc_, GetNativeHandle (),
reinterpret_cast<ULONG_PTR
> (
this)));
633#if qStroika_Foundation_Common_Platform_POSIX
634void Thread::Ptr::Rep_::InterruptionSignalHandler_ (SignalID signal)
noexcept
647#elif qStroika_Foundation_Common_Platform_Windows
648void CALLBACK Thread::Ptr::Rep_::CalledInRepThreadAbortProc_ (ULONG_PTR lpParameter)
651 [[maybe_unused]] Ptr::Rep_* rep =
reinterpret_cast<Ptr::Rep_*
> (lpParameter);
652 Require (GetCurrentThreadID () == rep->GetID ());
653 if (rep->fThrowInterruptExceptionInsideUserAPC_) [[unlikely]] {
673 if (cfg->fStackSize) {
676 if (cfg->fStackGuard) {
679#if qStroika_Foundation_Common_Platform_Windows
680 if (cfg->fThrowInterruptExceptionInsideUserAPC) {
681 result.fThrowInterruptExceptionInsideUserAPC = *cfg->fThrowInterruptExceptionInsideUserAPC;
692 AssertExternallySynchronizedMutex::ReadContext declareContext{fThisAssertExternallySynchronized_};
696 fRep_->fInitialPriority_.store (priority);
700 fRep_->ApplyPriority (priority);
706 AssertExternallySynchronizedMutex::ReadContext declareContext{fThisAssertExternallySynchronized_};
707 return fRep_ ==
nullptr ?
String{} : fRep_->fThreadName_;
713 AssertExternallySynchronizedMutex::ReadContext declareContext{fThisAssertExternallySynchronized_};
714#if USE_NOISY_TRACE_IN_THIS_MODULE_
715 TraceContextBumper ctx{
"Thread::SetThreadName",
"thisThreadID={}, threadName = '{}'"_f, GetID (), threadName};
717 if (fRep_->fThreadName_ != threadName) {
718 fRep_->fThreadName_ = threadName.
As<wstring> ();
719 fRep_->ApplyThreadName2OSThreadObject ();
725 AssertExternallySynchronizedMutex::ReadContext declareContext{fThisAssertExternallySynchronized_};
726 return fRep_ ==
nullptr ?
"nullptr"sv : fRep_->ToString ();
731 AssertExternallySynchronizedMutex::ReadContext declareContext{fThisAssertExternallySynchronized_};
734 Require (not fRep_->fStartEverInitiated_);
735#if qStroika_Foundation_Debug_AssertionsChecked
737 auto s = GetStatus ();
738 Require (s == Status::eNotYetRunning or s == Status::eAborting);
767 fRep_->fStartEverInitiated_ =
true;
768 if (fRep_->fAbortRequested_) [[unlikely]] {
772#if __cpp_lib_jthread >= 201911
773 fRep_->fStopToken_ = fRep_->fStopSource_.get_token ();
774 fRep_->fThread_ = jthread{[
this] () ->
void { Rep_::ThreadMain_ (fRep_); }};
776 fRep_->fThread_ = thread{[
this] () ->
void { Rep_::ThreadMain_ (fRep_); }};
778 fRep_->fThreadValid_ =
true;
781 fRep_->fRefCountBumpedInsideThreadMainEvent_.Wait ();
787 fRep_->ApplyThreadName2OSThreadObject ();
788 if (optional<Priority> p = fRep_->fInitialPriority_.load ()) {
789 fRep_->ApplyPriority (*p);
792 fRep_->fStartReadyToTransitionToRunningEvent_.Set ();
797 for (
auto s = GetStatus (); s != Status::eNotYetRunning; s = GetStatus ()) {
801 this_thread::yield ();
803#if qStroika_Foundation_Debug_AssertionsChecked
804 auto s = GetStatus ();
805 Ensure (s == Status::eRunning or s == Status::eAborting or s == Status::eCompleted);
812 Require (*
this !=
nullptr);
813 AssertExternallySynchronizedMutex::ReadContext declareContext{fThisAssertExternallySynchronized_};
815#if __cpp_lib_jthread >= 201911
816 bool wasAborted = fRep_->fAbortRequested_;
819 fRep_->fAbortRequested_ =
true;
820 if (fRep_->fStartEverInitiated_) {
821#if __cpp_lib_jthread >= 201911
824 if (not wasAborted) [[likely]] {
825 DbgTrace (
"Transitioned state to aborting, so calling fThread_.get_stop_source ().request_stop ();"_f);
826 fRep_->fStopSource_.request_stop ();
837 fRep_->fThreadDoneAndCanJoin_.Set ();
839 if (not IsDone ()) [[likely]] {
841 fRep_->NotifyOfInterruptionFromAnyThread_ ();
843#if USE_NOISY_TRACE_IN_THIS_MODULE_
844 DbgTrace (
"leaving *this = {}"_f, *
this);
851 "*this={}, timeoutAt={}"_f,
ToString (), timeoutAt)};
853 AssertExternallySynchronizedMutex::ReadContext declareContext{fThisAssertExternallySynchronized_};
861#if USE_NOISY_TRACE_IN_THIS_MODULE_
864 AssertExternallySynchronizedMutex::ReadContext declareContext{fThisAssertExternallySynchronized_};
865 if (fRep_ and fRep_->IsDone_ () and fRep_->fSavedException_.load () !=
nullptr) {
867 ReThrow (fRep_->fSavedException_.load (),
"Rethrowing exception across threads");
874 if (not WaitForDoneUntilQuietly (timeoutAt)) {
881#if USE_NOISY_TRACE_IN_THIS_MODULE_
883 "*this={}, timeoutAt={}"_f,
ToString (), timeoutAt)};
885 Require (*
this !=
nullptr);
886 AssertExternallySynchronizedMutex::ReadContext declareContext{fThisAssertExternallySynchronized_};
888 if (fRep_->fThreadDoneAndCanJoin_.WaitUntilQuietly (timeoutAt) == WaitableEvent::WaitStatus::eTriggered) {
899 if (fRep_->fThreadValid_ and fRep_->fThread_.joinable ()) {
901 fRep_->fThread_.join ();
905 Assert (timeoutAt <= Time::GetTickCount ());
909#if qStroika_Foundation_Common_Platform_Windows
912 AssertExternallySynchronizedMutex::ReadContext declareContext{fThisAssertExternallySynchronized_};
913 Require (*
this !=
nullptr);
915 HANDLE thread = fRep_->GetNativeHandle ();
916 if (thread == INVALID_HANDLE_VALUE) {
921 while (GetStatus () != Status::eCompleted) {
923 if (time2Wait <= 0s) {
937Thread::CleanupPtr::~CleanupPtr ()
939 if (*
this !=
nullptr) {
940 SuppressInterruptionInContext suppressInterruption;
955Thread::Ptr Thread::New (
const function<
void ()>& fun2CallOnce,
const optional<Characters::String>& name,
const optional<Configuration>& configuration)
958 Ptr ptr =
Ptr{make_shared<Ptr::Rep_> (fun2CallOnce, CombineCFGs_ (configuration))};
967 return sDefaultConfiguration_.load ();
972 auto result = sDefaultConfiguration_.load ();
973 if (newConfiguration) {
974 sDefaultConfiguration_.store (newConfiguration.value ());
979#if qStroika_Foundation_Execution_Thread_SupportThreadStatistics
980Thread::Statistics Thread::GetStatistics ()
982 [[maybe_unused]] lock_guard critSec{sThreadSupportStatsMutex_};
989#if USE_NOISY_TRACE_IN_THIS_MODULE_
997#if USE_NOISY_TRACE_IN_THIS_MODULE_
999 "threads={}, timeoutAt={}"_f, threads, timeoutAt)};
1010#if USE_NOISY_TRACE_IN_THIS_MODULE_
1019#if qStroika_Foundation_Common_Platform_POSIX
1021 SignalID sSignalUsedForThreadInterrupt_ = SIGUSR2;
1023SignalID Thread::SignalUsedForThreadInterrupt () noexcept
1025 return sSignalUsedForThreadInterrupt_;
1027SignalID Thread::SignalUsedForThreadInterrupt (optional<SignalID> signalNumber)
1029 SignalID result = sSignalUsedForThreadInterrupt_;
1031 [[maybe_unused]] lock_guard critSec{sHandlerInstalled_};
1032 if (sHandlerInstalled_) {
1034 sHandlerInstalled_ =
false;
1036 sSignalUsedForThreadInterrupt_ = signalNumber.value ();
1038 if (not sHandlerInstalled_) {
1040 sHandlerInstalled_ =
true;
1057string Thread::FormatThreadID_A (
Thread::IDType threadID,
const FormatThreadInfo& formatThreadInfo)
1068#if qStroika_Foundation_Common_Platform_Windows
1069 constexpr size_t kSizeOfThreadID_ =
sizeof (DWORD);
1070#elif qStroika_Foundation_Common_Platform_POSIX
1071 constexpr size_t kSizeOfThreadID_ =
sizeof (pthread_t);
1078 if constexpr (kSizeOfThreadID_ >=
sizeof (uint64_t)) {
1079 uint64_t threadIDInt = 0;
1081 return formatThreadInfo.fIncludeLeadingZeros ? Characters::CString::Format (
"0x%016llx", threadIDInt)
1082 : Characters::CString::Format (
"0x%llx", threadIDInt);
1085 uint32_t threadIDInt = 0;
1094 constexpr bool kUse16BitThreadIDsIfTheyFit_{
false};
1095 const bool kUse16Bit_ = kUse16BitThreadIDsIfTheyFit_ and threadIDInt <= 0xffff;
1097 return formatThreadInfo.fIncludeLeadingZeros ? Characters::CString::Format (
"0x%04x", threadIDInt)
1098 : Characters::CString::Format (
"0x%x", threadIDInt);
1101 return formatThreadInfo.fIncludeLeadingZeros ? Characters::CString::Format (
"0x%08x", threadIDInt)
1102 : Characters::CString::Format (
"0x%x", threadIDInt);
1107#if qCompilerAndStdLib_ThreadLocalInlineDupSymbol_Buggy
1108#if __cpp_lib_jthread >= 201911
1114optional<stop_token> Thread::GetCurrentThreadStopToken ()
1117 return curThread.GetStopToken ();
1126#if qCompilerAndStdLib_ThreadLocalInlineDupSymbol_Buggy
1150 if (shared_ptr<Ptr::Rep_> thisRunningThreadRep =
1151#
if qCompilerAndStdLib_thread_local_static_inline_twice_Buggy
1152 Ptr::sCurrentThreadRep_BWA_ ().lock ()
1154 Ptr::sCurrentThreadRep_.lock ()
1157 if (t_InterruptionSuppressDepth_ == 0) [[likely]] {
1158 if (thisRunningThreadRep->fAbortRequested_) [[unlikely]] {
1159 Throw (Thread::AbortException::kThe);
1162#if qStroika_Foundation_Debug_DefaultTracingOn
1163 else if (thisRunningThreadRep->fAbortRequested_) {
1164 static atomic<unsigned int> sSuperSuppress_{};
1165 if (++sSuperSuppress_ <= 1) {
1166 IgnoreExceptionsForCall (
DbgTrace (
"Suppressed interrupt throw: t_InterruptionSuppressDepth_={}, t_Interrupting_={}"_f,
1167 t_InterruptionSuppressDepth_, thisRunningThreadRep->fAbortRequested_.load ()));
1188 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 & Get()
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