Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
TThread.cxx
Go to the documentation of this file.
1// @(#)root/thread:$Id$
2// Author: Fons Rademakers 02/07/97
3
4/*************************************************************************
5 * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
6 * All rights reserved. *
7 * *
8 * For the licensing terms see $ROOTSYS/LICENSE. *
9 * For the list of contributors see $ROOTSYS/README/CREDITS. *
10 *************************************************************************/
11
12/** \class TThread
13
14\legacy{TThread}
15
16This class implements threads. A thread is an execution environment
17much lighter than a process. A single process can have multiple
18threads. The actual work is done via the TThreadImp class (either
19TPosixThread or TWin32Thread).
20
21**/
22
23#include "RConfigure.h"
24
25#include "TThread.h"
26#include "TThreadImp.h"
27#include "TThreadFactory.h"
28#include "TROOT.h"
29#include "TCondition.h"
30#include "TApplication.h"
31#include "TVirtualPad.h"
32#include "TMethodCall.h"
33#include "TMutex.h"
34#include "TTimeStamp.h"
35#include "TInterpreter.h"
36#include "TError.h"
37#include "TSystem.h"
38#include "Varargs.h"
39#include "ThreadLocalStorage.h"
40#include "TThreadSlots.h"
41#include "TRWMutexImp.h"
42#include "snprintf.h"
43
46TThread *TThread::fgMain = nullptr;
48std::atomic<char *> volatile TThread::fgXAct{nullptr};
51void **volatile TThread::fgXArr = nullptr;
52volatile Int_t TThread::fgXAnb = 0;
53volatile Int_t TThread::fgXArt = 0;
54
55static void CINT_alloc_lock() { gGlobalMutex->Lock(); }
57
58static TMutex *gMainInternalMutex = nullptr;
59
62
64
65extern "C" void ROOT_TThread_Initialize()
66{
68};
69
70//------------------------------------------------------------------------------
71
72// Set gGlobalMutex to 0 when Thread library gets unloaded
74public:
77 // Note: we could insert here a wait for all thread to be finished.
78 // this is questionable though as we need to balance between fixing a
79 // user error (the thread was let lose and the caller did not explicit wait)
80 // and the risk that we can not terminate a failing process.
81
84 gGlobalMutex = nullptr;
85 delete m;
87 TThread::fgThreadImp = nullptr;
88 delete imp;
89 }
90};
92
93//------------------------------------------------------------------------------
94
96private:
99 void **fRet;
104
105 static void* JoinFunc(void *p);
106
107public:
108 TJoinHelper(TThread *th, void **ret);
109 ~TJoinHelper();
110
111 Int_t Join();
112};
113
114////////////////////////////////////////////////////////////////////////////////
115/// Constructor of Thread helper class.
116
118 : fT(th), fRet(ret), fRc(0), fM(new TMutex), fC(new TCondition(fM)), fJoined(kFALSE)
119{
120 fH = new TThread("JoinHelper", JoinFunc, this);
121}
122
123////////////////////////////////////////////////////////////////////////////////
124/// Destructor.
125
127{
128 delete fC;
129 delete fM;
130 delete fH;
131}
132
133////////////////////////////////////////////////////////////////////////////////
134/// Static method which runs in a separate thread to handle thread
135/// joins without blocking the main thread.
136/// Return a value (zero) so that it makes a joinable thread.
137
139{
141
142 jp->fRc = jp->fT->Join(jp->fRet);
143
144 jp->fM->Lock();
145 jp->fJoined = kTRUE;
146 jp->fC->Signal();
147 jp->fM->UnLock();
148
149 TThread::Exit(nullptr);
150
151 return nullptr;
152}
153
154////////////////////////////////////////////////////////////////////////////////
155/// Thread join function.
156
158{
159 fM->Lock();
160 fH->Run();
161
162 while (kTRUE) {
163 // TimedWaitRelative will release the mutex (i.e. equivalent to fM->Unlock),
164 // then block on the condition variable. Upon return it will lock the mutex.
165 int r = fC->TimedWaitRelative(100); // 100 ms
166
167 // From the man page from pthread_ond_timedwait:
168
169 // When using condition variables there is always a Boolean predicate
170 // involving shared variables associated with each condition wait that
171 // is true if the thread should proceed. Spurious wakeups from the
172 // pthread_cond_timedwait() or pthread_cond_wait() functions may occur.
173 // Since the return from pthread_cond_timedwait() or pthread_cond_wait()
174 // does not imply anything about the value of this predicate, the
175 // predicate should be re-evaluated upon such return.
176
177 if (r == 0 || r == 1) {
178 // If we received the signal or timed out, let's check the value
179 if (fJoined) break;
180 } else {
181 // If any other error occurred, there is no point in trying again
182 break;
183 }
184
186 }
187
188 fM->UnLock();
189
190 // And wait for the help to finish to avoid the risk that it is still
191 // running when the main tread is finished (and the thread library unloaded!)
192 TThread::fgThreadImp->Join(fH, nullptr);
193
194 return fRc;
195}
196
197
198//------------------------------------------------------------------------------
199
201
202
203////////////////////////////////////////////////////////////////////////////////
204/// Create a thread. Specify the function or static class method
205/// to be executed by the thread and a pointer to the argument structure.
206/// The user function should return a void*. To start the thread call Run().
207
208TThread::TThread(VoidRtnFunc_t fn, void *arg, EPriority pri)
209 : TNamed("<anon>", "")
210{
212 fFcnVoid = nullptr;
213 fFcnRetn = fn;
214 fPriority = pri;
215 fThreadArg = arg;
216 Constructor();
217 fNamed = kFALSE;
218}
219
220////////////////////////////////////////////////////////////////////////////////
221/// Create a detached thread. Specify the function or static class method
222/// to be executed by the thread and a pointer to the argument structure.
223/// To start the thread call Run().
224
225TThread::TThread(VoidFunc_t fn, void *arg, EPriority pri)
226 : TNamed("<anon>", "")
227{
229 fFcnRetn = nullptr;
230 fFcnVoid = fn;
231 fPriority = pri;
232 fThreadArg = arg;
233 Constructor();
234 fNamed = kFALSE;
235}
236
237////////////////////////////////////////////////////////////////////////////////
238/// Create thread with a name. Specify the function or static class method
239/// to be executed by the thread and a pointer to the argument structure.
240/// The user function should return a void*. To start the thread call Run().
241
242TThread::TThread(const char *thname, VoidRtnFunc_t fn, void *arg,
243 EPriority pri) : TNamed(thname, "")
244{
246 fFcnVoid = nullptr;
247 fFcnRetn = fn;
248 fPriority = pri;
249 fThreadArg = arg;
250 Constructor();
251 fNamed = kTRUE;
252}
253
254////////////////////////////////////////////////////////////////////////////////
255/// Create a detached thread with a name. Specify the function or static
256/// class method to be executed by the thread and a pointer to the argument
257/// structure. To start the thread call Run().
258
259TThread::TThread(const char *thname, VoidFunc_t fn, void *arg,
260 EPriority pri) : TNamed(thname, "")
261{
263 fFcnRetn = nullptr;
264 fFcnVoid = fn;
265 fPriority = pri;
266 fThreadArg = arg;
267 Constructor();
268 fNamed = kTRUE;
269}
270
271////////////////////////////////////////////////////////////////////////////////
272/// Create a TThread for a already running thread.
273
275{
277 fFcnRetn = nullptr;
278 fFcnVoid = nullptr;
280 fThreadArg = nullptr;
281 Constructor();
282
283 // Changing the id must be protected as it will be look at by multiple
284 // threads (see TThread::GetThread)
286 fNamed = kFALSE;
287 fId = (id ? id : SelfId());
290
291 if (gDebug)
292 Info("TThread::TThread", "TThread attached to running thread");
293}
294
295////////////////////////////////////////////////////////////////////////////////
296/// Initialize the Thread package. This initializes the TThread and ROOT
297/// global mutexes to make parts of ROOT thread safe/aware. This call is
298/// implicit in case a TThread is created.
299
301{
302 Init();
303}
304
305////////////////////////////////////////////////////////////////////////////////
306/// Return true, if the TThread objects have been initialize. If false,
307/// the process is (from ROOT's point of view) single threaded.
308
310{
311 if (fgThreadImp)
312 return kTRUE;
313 return kFALSE;
314}
315
316////////////////////////////////////////////////////////////////////////////////
317/// Initialize global state and variables once.
318
320{
321 if (fgThreadImp || fgIsTearDown) return;
322
323 // 'Insure' gROOT is created before initializing the Thread safe behavior
324 // (to make sure we do not have two attempting to create it).
326
329
330 fgMainId = fgThreadImp->SelfId();
331 fgMainMutex = new TMutex(kTRUE);
334
335
336 // Create the single global mutex
338 // We need to make sure that gCling is initialized.
339 TInterpreter::Instance()->SetAlloclockfunc(CINT_alloc_lock);
341
342 // To avoid deadlocks, gInterpreterMutex and gROOTMutex need
343 // to point at the same instance.
344 // Both are now deprecated in favor of ROOT::gCoreMutex
345 {
347 if (!ROOT::gCoreMutex) {
348 // To avoid dead locks, caused by shared library opening and/or static initialization
349 // taking the same lock as 'tls_get_addr_tail', we can not use UniqueLockRecurseCount.
350#ifdef R__HAS_TBB
352#else
354#endif
355 }
358 }
359}
360
361////////////////////////////////////////////////////////////////////////////////
362/// Common thread constructor.
363
365{
366 fHolder = nullptr;
367 fClean = nullptr;
369
370 fId = -1;
371 fHandle= 0;
372 if (!fgThreadImp) Init();
373
374 SetComment("Constructor: MainInternalMutex Locking");
376 SetComment("Constructor: MainInternalMutex Locked");
377
378 if (fgMain) fgMain->fPrev = this;
379 fNext = fgMain;
380 fPrev = nullptr;
381 fgMain = this;
382
384 SetComment();
385
386 // thread is set up in initialisation routine or Run().
387}
388
389////////////////////////////////////////////////////////////////////////////////
390/// Cleanup the thread.
391
393{
394 if (gDebug)
395 Info("TThread::~TThread", "thread deleted");
396
397 // Disconnect thread instance
398
399 SetComment("Destructor: MainInternalMutex Locking");
401 SetComment("Destructor: MainInternalMutex Locked");
402
403 if (fPrev) fPrev->fNext = fNext;
404 if (fNext) fNext->fPrev = fPrev;
405 if (fgMain == this) fgMain = fNext;
406
408 SetComment();
409 if (fHolder)
410 *fHolder = nullptr;
411}
412
413////////////////////////////////////////////////////////////////////////////////
414/// Static method to delete the specified thread.
415/// Returns -1 in case the thread was running and has been killed. Returns
416/// 0 in case the thread has been Delete and Cleaned up. The th pointer is
417/// not valid anymore in that case.
418
420{
421 if (!th) return 0;
422 th->fHolder = &th;
423
424 if (th->fState == kRunningState) { // Cancel if running
426
427 if (gDebug)
428 th->Info("TThread::Delete", "deleting thread");
429
430 th->Kill();
431 return -1;
432 }
433
434 CleanUp();
435 return 0;
436}
437
438////////////////////////////////////////////////////////////////////////////////
439/// Static method to check if threads exist.
440/// Returns the number of running threads.
441
443{
445
446 Int_t num = 0;
447 for (TThread *l = fgMain; l; l = l->fNext)
448 num++; //count threads
449
451
452 return num;
453}
454
455////////////////////////////////////////////////////////////////////////////////
456/// Set thread priority.
457
462
463////////////////////////////////////////////////////////////////////////////////
464/// Static method to find a thread by id.
465
467{
468 TThread *myTh;
469
471
472 for (myTh = fgMain; myTh && (myTh->fId != id); myTh = myTh->fNext) { }
473
475
476 return myTh;
477}
478
479////////////////////////////////////////////////////////////////////////////////
480/// Static method to find a thread by name.
481
483{
484 TThread *myTh;
485
487
488 for (myTh = fgMain; myTh && (strcmp(name, myTh->GetName())); myTh = myTh->fNext) { }
489
491
492 return myTh;
493}
494
495////////////////////////////////////////////////////////////////////////////////
496/// Static method returning pointer to current thread.
497
499{
500 TTHREAD_TLS(TThread *) self = nullptr;
501
502 if (!self || fgIsTearDown) {
503 if (fgIsTearDown)
504 self = nullptr;
505 self = GetThread(SelfId());
506 }
507 return self;
508}
509
510
511////////////////////////////////////////////////////////////////////////////////
512/// Join this thread.
513
515{
516 if (fId == -1) {
517 Error("Join", "thread not running");
518 return -1;
519 }
520
521 if (fDetached) {
522 Error("Join", "cannot join detached thread");
523 return -1;
524 }
525
526 if (SelfId() != fgMainId)
527 return fgThreadImp->Join(this, ret);
528
529 // do not block the main thread, use helper thread
530 TJoinHelper helper(this, ret);
531
532 return helper.Join();
533}
534
535////////////////////////////////////////////////////////////////////////////////
536/// Static method to join a thread by id.
537
539{
541
542 if (!myTh) {
543 ::Error("TThread::Join", "cannot find thread 0x%lx", jid);
544 return -1L;
545 }
546
547 return myTh->Join(ret);
548}
549
550////////////////////////////////////////////////////////////////////////////////
551/// Static method returning the id for the current thread.
552
554{
555 if (fgIsTearDown) return -1;
556 if (!fgThreadImp) Init();
557
558 return fgThreadImp->SelfId();
559}
560
561////////////////////////////////////////////////////////////////////////////////
562/// Start the thread. This starts the static method TThread::Function()
563/// which calls the user function specified in the TThread ctor with
564/// the arg argument.
565/// If affinity is specified (>=0), a CPU affinity will be associated
566/// with the current thread.
567/// Returns 0 on success, otherwise an error number will
568/// be returned.
569
570Int_t TThread::Run(void *arg, const int affinity)
571{
572 if (arg) fThreadArg = arg;
573
574 SetComment("Run: MainInternalMutex locking");
576 SetComment("Run: MainMutex locked");
577
578 int iret = fgThreadImp->Run(this, affinity);
579
581
582 if (gDebug)
583 Info("TThread::Run", "thread run requested");
584
586 SetComment();
587 return iret;
588}
589
590////////////////////////////////////////////////////////////////////////////////
591/// Kill this thread. Returns 0 on success, otherwise an error number will
592/// be returned.
593
595{
597 if (gDebug)
598 Warning("TThread::Kill", "thread is not running");
599 return 13;
600 } else {
602 return fgThreadImp->Kill(this);
603 }
604}
605
606////////////////////////////////////////////////////////////////////////////////
607/// Static method to kill the thread by id. Returns 0 on success, otherwise
608/// an error number will be returned.
609
611{
612 TThread *th = GetThread(id);
613 if (th) {
614 return fgThreadImp->Kill(th);
615 } else {
616 if (gDebug)
617 ::Warning("TThread::Kill(Long_t)", "thread 0x%lx not found", id);
618 return 13;
619 }
620}
621
622////////////////////////////////////////////////////////////////////////////////
623/// Static method to kill thread by name. Returns 0 on success, otherwise
624/// an error number will be returned.
625
627{
628 TThread *th = GetThread(name);
629 if (th) {
630 return fgThreadImp->Kill(th);
631 } else {
632 if (gDebug)
633 ::Warning("TThread::Kill(const char*)", "thread %s not found", name);
634 return 13;
635 }
636}
637
638////////////////////////////////////////////////////////////////////////////////
639/// Static method to turn off thread cancellation. Returns 0 on success,
640/// otherwise an error number will be returned.
641
643{
644 return fgThreadImp ? fgThreadImp->SetCancelOff() : -1;
645}
646
647////////////////////////////////////////////////////////////////////////////////
648/// Static method to turn on thread cancellation. Returns 0 on success,
649/// otherwise an error number will be returned.
650
652{
653 return fgThreadImp ? fgThreadImp->SetCancelOn() : -1;
654}
655
656////////////////////////////////////////////////////////////////////////////////
657/// Static method to set the cancellation response type of the calling thread
658/// to asynchronous, i.e. cancel as soon as the cancellation request
659/// is received.
660
662{
663 return fgThreadImp ? fgThreadImp->SetCancelAsynchronous() : -1;
664}
665
666////////////////////////////////////////////////////////////////////////////////
667/// Static method to set the cancellation response type of the calling thread
668/// to deferred, i.e. cancel only at next cancellation point.
669/// Returns 0 on success, otherwise an error number will be returned.
670
672{
673 return fgThreadImp ? fgThreadImp->SetCancelDeferred() : -1;
674}
675
676////////////////////////////////////////////////////////////////////////////////
677/// Static method to set a cancellation point. Returns 0 on success, otherwise
678/// an error number will be returned.
679
681{
682 return fgThreadImp ? fgThreadImp->CancelPoint() : -1;
683}
684
685////////////////////////////////////////////////////////////////////////////////
686/// Static method which pushes thread cleanup method on stack.
687/// Returns 0 in case of success and -1 in case of error.
688
689Int_t TThread::CleanUpPush(void *free, void *arg)
690{
691 TThread *th = Self();
692 if (th)
693 return fgThreadImp->CleanUpPush(&(th->fClean), free, arg);
694 return -1;
695}
696
697////////////////////////////////////////////////////////////////////////////////
698/// Static method which pops thread cleanup method off stack.
699/// Returns 0 in case of success and -1 in case of error.
700
702{
703 TThread *th = Self();
704 if (th)
705 return fgThreadImp->CleanUpPop(&(th->fClean), exe);
706 return -1;
707}
708
709////////////////////////////////////////////////////////////////////////////////
710/// Static method to cleanup the calling thread.
711
713{
714 TThread *th = Self();
715 if (!th) return 13;
716
717 fgThreadImp->CleanUp(&(th->fClean));
718 fgMainMutex->CleanUp();
719 if (fgXActMutex)
720 fgXActMutex->CleanUp();
721
722 gMainInternalMutex->CleanUp();
723
724 if (th->fHolder)
725 delete th;
726
727 return 0;
728}
729
730////////////////////////////////////////////////////////////////////////////////
731/// Static method which is called after the thread has been canceled.
732
734{
735 if (th) {
737 if (gDebug)
738 th->Info("TThread::AfterCancel", "thread is canceled");
739 } else
740 ::Error("TThread::AfterCancel", "zero thread pointer passed");
741}
742
743////////////////////////////////////////////////////////////////////////////////
744/// Static method which terminates the execution of the calling thread.
745
747{
748 return fgThreadImp ? fgThreadImp->Exit(ret) : -1;
749}
750
751////////////////////////////////////////////////////////////////////////////////
752/// Static method to sleep the calling thread.
753
755{
756 UInt_t ms = UInt_t(secs * 1000) + UInt_t(nanos / 1000000);
757 if (gSystem) gSystem->Sleep(ms);
758 return 0;
759}
760
761////////////////////////////////////////////////////////////////////////////////
762/// Static method to get the current time. Returns
763/// the number of seconds.
764
766{
767 TTimeStamp t;
768 if (absSec) *absSec = t.GetSec();
769 if (absNanoSec) *absNanoSec = t.GetNanoSec();
770 return t.GetSec();
771}
772
773////////////////////////////////////////////////////////////////////////////////
774/// Static method to lock the main thread mutex.
775
777{
778 return (fgMainMutex ? fgMainMutex->Lock() : 0);
779}
780
781////////////////////////////////////////////////////////////////////////////////
782/// Static method to try to lock the main thread mutex.
783
785{
786 return (fgMainMutex ? fgMainMutex->TryLock() : 0);
787}
788
789////////////////////////////////////////////////////////////////////////////////
790/// Static method to unlock the main thread mutex.
791
793{
794 return (fgMainMutex ? fgMainMutex->UnLock() : 0);
795}
796
797////////////////////////////////////////////////////////////////////////////////
798/// Static method which is called by the system thread function and
799/// which in turn calls the actual user function.
800
801void *TThread::Function(void *ptr)
802{
803 TThread *th;
804 void *ret, *arg;
805
806 TThreadCleaner dummy;
807
808 th = (TThread *)ptr;
809
810 // Default cancel state is OFF
811 // Default cancel type is DEFERRED
812 // User can change it by call SetCancelOn() and SetCancelAsynchronous()
813 SetCancelOff();
815 CleanUpPush((void *)&AfterCancel, th); // Enable standard cancelling function
816
817 if (gDebug)
818 th->Info("TThread::Function", "thread is running");
819
820 arg = th->fThreadArg;
821 th->fState = kRunningState;
822
823 if (th->fDetached) {
824 //Detached, non joinable thread
825 (th->fFcnVoid)(arg);
826 ret = nullptr;
828 } else {
829 //UnDetached, joinable thread
830 ret = (th->fFcnRetn)(arg);
832 }
833
834 CleanUpPop(1); // Disable standard canceling function
835
836 if (gDebug)
837 th->Info("TThread::Function", "thread has finished");
838
840
841 return ret;
842}
843
844////////////////////////////////////////////////////////////////////////////////
845/// Static method listing the existing threads.
846
848{
849 TThread *l;
850 int i;
851
852 if (!fgMain) {
853 ::Info("TThread::Ps", "no threads have been created");
854 return;
855 }
856
858
859 int num = 0;
860 for (l = fgMain; l; l = l->fNext)
861 num++;
862
863 char cbuf[256];
864 printf(" Thread State\n");
865 for (l = fgMain; l; l = l->fNext) { // loop over threads
866 memset(cbuf, ' ', sizeof(cbuf));
867 snprintf(cbuf, sizeof(cbuf), "%3d %s:0x%lx", num--, l->GetName(), l->fId);
868 i = (int)strlen(cbuf);
869 if (i < 30)
870 cbuf[i] = ' ';
871 cbuf[30] = 0;
872 printf("%30s", cbuf);
873
874 switch (l->fState) { // print states
875 case kNewState: printf("Idle "); break;
876 case kRunningState: printf("Running "); break;
877 case kTerminatedState: printf("Terminated "); break;
878 case kFinishedState: printf("Finished "); break;
879 case kCancelingState: printf("Canceling "); break;
880 case kCanceledState: printf("Canceled "); break;
881 case kDeletingState: printf("Deleting "); break;
882 default: printf("Invalid ");
883 }
884 if (l->fComment[0]) printf(" // %s", l->fComment);
885 printf("\n");
886 } // end of loop
887
889}
890
891////////////////////////////////////////////////////////////////////////////////
892/// Static method returning a pointer to thread specific data container
893/// of the calling thread.
894/// k should be between 0 and kMaxUserThreadSlot for user application.
895/// (and between kMaxUserThreadSlot and kMaxThreadSlot for ROOT libraries).
896/// See ROOT::EThreadSlotReservation
897
898void **TThread::Tsd(void *dflt, Int_t k)
899{
900 if (TThread::SelfId() == fgMainId) { //Main thread
901 return (void**)dflt;
902 } else {
903 return GetTls(k);
904 }
905}
906
907////////////////////////////////////////////////////////////////////////////////
908/// Static method that initializes the TLS array of a thread and returns the
909/// reference to a given position in that array.
910
913
914 return &(tls[k]);
915}
916
917////////////////////////////////////////////////////////////////////////////////
918/// Static method providing a thread safe printf. Appends a newline.
919
920void TThread::Printf(const char *va_(fmt), ...)
921{
922 va_list ap;
923 va_start(ap,va_(fmt));
924
925 Int_t buf_size = 2048;
926 char *buf;
927
928again:
929 buf = new char[buf_size];
930
931 int n = vsnprintf(buf, buf_size, va_(fmt), ap);
932 // old vsnprintf's return -1 if string is truncated new ones return
933 // total number of characters that would have been written
934 if (n == -1 || n >= buf_size) {
935 buf_size *= 2;
936 delete [] buf;
937 goto again;
938 }
939
940 va_end(ap);
941
942 void *arr[2];
943 arr[1] = (void*) buf;
944 if (XARequest("PRTF", 2, arr, nullptr)) {
945 delete [] buf;
946 return;
947 }
948
949 printf("%s\n", buf);
950 fflush(stdout);
951
952 delete [] buf;
953}
954
955////////////////////////////////////////////////////////////////////////////////
956/// Thread specific error handler function.
957/// It calls the user set error handler in the main thread.
958
959void TThread::ErrorHandler(int level, const char *location, const char *fmt,
960 va_list ap) const
961{
962 Int_t buf_size = 2048;
963 char *buf, *bp;
964
965again:
966 buf = new char[buf_size];
967
968 int n = vsnprintf(buf, buf_size, fmt, ap);
969 // old vsnprintf's return -1 if string is truncated new ones return
970 // total number of characters that would have been written
971 if (n == -1 || n >= buf_size) {
972 buf_size *= 2;
973 delete [] buf;
974 goto again;
975 }
976 if (level >= kSysError && level < kFatal) {
977 const std::size_t bufferSize = buf_size + strlen(gSystem->GetError()) + 5;
978 char *buf1 = new char[bufferSize];
979 snprintf(buf1, bufferSize, "%s (%s)", buf, gSystem->GetError());
980 bp = buf1;
981 delete [] buf;
982 } else
983 bp = buf;
984
985 void *arr[4];
986 arr[1] = (void*) Longptr_t(level);
987 arr[2] = (void*) location;
988 arr[3] = (void*) bp;
989 if (XARequest("ERRO", 4, arr, nullptr))
990 return;
991
992 if (level != kFatal)
993 ::GetErrorHandler()(level, level >= gErrorAbortLevel, location, bp);
994 else
995 ::GetErrorHandler()(level, kTRUE, location, bp);
996
997 delete [] bp;
998}
999
1000////////////////////////////////////////////////////////////////////////////////
1001/// Interface to ErrorHandler. User has to specify the class name as
1002/// part of the location, just like for the global Info(), Warning() and
1003/// Error() functions.
1004
1005void TThread::DoError(int level, const char *location, const char *fmt,
1006 va_list va) const
1007{
1008 char *loc = nullptr;
1009
1010 if (location) {
1011 const std::size_t bufferSize = strlen(location) + strlen(GetName()) + 32;
1012 loc = new char[bufferSize];
1013 snprintf(loc, bufferSize, "%s %s:0x%lx", location, GetName(), fId);
1014 } else {
1015 const std::size_t bufferSize = strlen(GetName()) + 32;
1016 loc = new char[bufferSize];
1017 snprintf(loc, bufferSize, "%s:0x%lx", GetName(), fId);
1018 }
1019
1020 ErrorHandler(level, loc, fmt, va);
1021
1022 delete [] loc;
1023}
1024
1025////////////////////////////////////////////////////////////////////////////////
1026/// Static method used to allow commands to be executed by the main thread.
1027
1029{
1030 if (!gApplication || !gApplication->IsRunning()) return 0;
1031
1032 // The first time, create the related static vars
1033 if (!fgXActMutex && gGlobalMutex) {
1034 gGlobalMutex->Lock();
1035 if (!fgXActMutex) {
1036 fgXActMutex = new TMutex(kTRUE);
1037 fgXActCondi = new TCondition;
1038 new TThreadTimer;
1039 }
1041 }
1042
1043 TThread *th = Self();
1044 if (th && th->fId != fgMainId) { // we are in the thread
1045 th->SetComment("XARequest: XActMutex Locking");
1046 fgXActMutex->Lock();
1047 th->SetComment("XARequest: XActMutex Locked");
1048
1049 TConditionImp *condimp = fgXActCondi->fConditionImp;
1050 TMutexImp *condmutex = fgXActCondi->GetMutex()->fMutexImp;
1051
1052 // Lock now, so the XAction signal will wait
1053 // and never come before the wait
1054 condmutex->Lock();
1055
1056 fgXAnb = nb;
1057 fgXArr = ar;
1058 fgXArt = 0;
1059 fgXAct = (char*) xact;
1060 th->SetComment(fgXAct);
1061
1062 if (condimp) condimp->Wait();
1063 condmutex->UnLock();
1064
1065 if (iret) *iret = fgXArt;
1066 fgXActMutex->UnLock();
1067 th->SetComment();
1068 return 1997;
1069 } else //we are in the main thread
1070 return 0;
1071}
1072
1073////////////////////////////////////////////////////////////////////////////////
1074/// Static method called via the thread timer to execute in the main
1075/// thread certain commands. This to avoid sophisticated locking and
1076/// possible deadlocking.
1077
1079{
1080 TConditionImp *condimp = fgXActCondi->fConditionImp;
1081 TMutexImp *condmutex = fgXActCondi->GetMutex()->fMutexImp;
1082 condmutex->Lock();
1083
1084 char const acts[] = "PRTF CUPD CANV CDEL PDCD METH ERRO";
1085 enum { kPRTF = 0, kCUPD = 5, kCANV = 10, kCDEL = 15,
1086 kPDCD = 20, kMETH = 25, kERRO = 30 };
1087 int iact = strstr(acts, fgXAct) - acts;
1088 TString cmd;
1089
1090 switch (iact) {
1091
1092 case kPRTF:
1093 printf("%s\n", (const char*)fgXArr[1]);
1094 fflush(stdout);
1095 break;
1096
1097 case kERRO:
1098 {
1099 int level = (int)Longptr_t(fgXArr[1]);
1100 const char *location = (const char*)fgXArr[2];
1101 char *mess = (char*)fgXArr[3];
1102 if (level != kFatal)
1103 GetErrorHandler()(level, level >= gErrorAbortLevel, location, mess);
1104 else
1105 GetErrorHandler()(level, kTRUE, location, mess);
1106 delete [] mess;
1107 }
1108 break;
1109
1110 case kCUPD:
1111 //((TCanvas *)fgXArr[1])->Update();
1113 void (*fFuncPtr)(void*);
1114 void* fVoidPtr;
1116 castFromFuncToVoidPtr.fVoidPtr = fgXArr[2];
1117 (*castFromFuncToVoidPtr.fFuncPtr)(fgXArr[1]); // aka TCanvas::Update()
1118 break;
1119
1120 case kCANV:
1121
1122 switch(fgXAnb) { // Over TCanvas constructors
1123
1124 case 2:
1125 //((TCanvas*)fgXArr[1])->Constructor();
1126 cmd.Form("((TCanvas *)0x%zx)->Constructor();",(size_t)fgXArr[1]);
1127 gROOT->ProcessLine(cmd.Data());
1128 break;
1129
1130 case 5:
1131 //((TCanvas*)fgXArr[1])->Constructor(
1132 // (char*)fgXArr[2],
1133 // (char*)fgXArr[3],
1134 // *((Int_t*)(fgXArr[4])));
1135 cmd.Form("((TCanvas *)0x%zx)->Constructor((char*)0x%zx,(char*)0x%zx,*((Int_t*)(0x%zx)));",(size_t)fgXArr[1],(size_t)fgXArr[2],(size_t)fgXArr[3],(size_t)fgXArr[4]);
1136 gROOT->ProcessLine(cmd.Data());
1137 break;
1138 case 6:
1139 //((TCanvas*)fgXArr[1])->Constructor(
1140 // (char*)fgXArr[2],
1141 // (char*)fgXArr[3],
1142 // *((Int_t*)(fgXArr[4])),
1143 // *((Int_t*)(fgXArr[5])));
1144 cmd.Form("((TCanvas *)0x%zx)->Constructor((char*)0x%zx,(char*)0x%zx,*((Int_t*)(0x%zx)),*((Int_t*)(0x%zx)));",(size_t)fgXArr[1],(size_t)fgXArr[2],(size_t)fgXArr[3],(size_t)fgXArr[4],(size_t)fgXArr[5]);
1145 gROOT->ProcessLine(cmd.Data());
1146 break;
1147
1148 case 8:
1149 //((TCanvas*)fgXArr[1])->Constructor(
1150 // (char*)fgXArr[2],
1151 // (char*)fgXArr[3],
1152 // *((Int_t*)(fgXArr[4])),
1153 // *((Int_t*)(fgXArr[5])),
1154 // *((Int_t*)(fgXArr[6])),
1155 // *((Int_t*)(fgXArr[7])));
1156 cmd.Form("((TCanvas *)0x%zx)->Constructor((char*)0x%zx,(char*)0x%zx,*((Int_t*)(0x%zx)),*((Int_t*)(0x%zx)),*((Int_t*)(0x%zx)),*((Int_t*)(0x%zx)));",(size_t)fgXArr[1],(size_t)fgXArr[2],(size_t)fgXArr[3],(size_t)fgXArr[4],(size_t)fgXArr[5],(size_t)fgXArr[6],(size_t)fgXArr[7]);
1157 gROOT->ProcessLine(cmd.Data());
1158 break;
1159
1160 }
1161 break;
1162
1163 case kCDEL:
1164 //((TCanvas*)fgXArr[1])->Destructor();
1165 cmd.Form("((TCanvas *)0x%zx)->Destructor();",(size_t)fgXArr[1]);
1166 gROOT->ProcessLine(cmd.Data());
1167 break;
1168
1169 case kPDCD:
1170 ((TVirtualPad*) fgXArr[1])->Divide( *((Int_t*)(fgXArr[2])),
1171 *((Int_t*)(fgXArr[3])),
1172 *((Float_t*)(fgXArr[4])),
1173 *((Float_t*)(fgXArr[5])),
1174 *((Int_t*)(fgXArr[6])));
1175 break;
1176 case kMETH:
1177 ((TMethodCall *) fgXArr[1])->Execute((void*)(fgXArr[2]),(const char*)(fgXArr[3]));
1178 break;
1179
1180 default:
1181 ::Error("TThread::XAction", "wrong case");
1182 }
1183
1184 fgXAct = nullptr;
1185 if (condimp) condimp->Signal();
1186 condmutex->UnLock();
1187}
1188
1189
1190//////////////////////////////////////////////////////////////////////////
1191// //
1192// TThreadTimer //
1193// //
1194//////////////////////////////////////////////////////////////////////////
1195
1196////////////////////////////////////////////////////////////////////////////////
1197/// Create thread timer.
1198
1200{
1201 gSystem->AddTimer(this);
1202}
1203
1204////////////////////////////////////////////////////////////////////////////////
1205/// Periodically execute the TThread::XAction() method in the main thread.
1206
1208{
1210 Reset();
1211
1212 return kFALSE;
1213}
1214
1215
1216//////////////////////////////////////////////////////////////////////////
1217// //
1218// TThreadCleaner //
1219// //
1220//////////////////////////////////////////////////////////////////////////
1221
1222////////////////////////////////////////////////////////////////////////////////
1223/// Call user clean up routines.
1224
bool Bool_t
Definition RtypesCore.h:63
int Int_t
Definition RtypesCore.h:45
long Longptr_t
Definition RtypesCore.h:75
unsigned long ULong_t
Definition RtypesCore.h:55
long Long_t
Definition RtypesCore.h:54
unsigned int UInt_t
Definition RtypesCore.h:46
float Float_t
Definition RtypesCore.h:57
constexpr Bool_t kFALSE
Definition RtypesCore.h:94
constexpr Bool_t kTRUE
Definition RtypesCore.h:93
#define ClassImp(name)
Definition Rtypes.h:374
R__EXTERN TApplication * gApplication
ROOT::Detail::TRangeCast< T, true > TRangeDynCast
TRangeDynCast is an adapter class that allows the typed iteration through a TCollection.
Int_t gErrorAbortLevel
Definition TError.cxx:32
ErrorHandlerFunc_t GetErrorHandler()
Returns the current error handler function.
Definition TError.cxx:100
constexpr Int_t kFatal
Definition TError.h:50
constexpr Int_t kSysError
Definition TError.h:49
winID h TVirtualViewer3D TVirtualGLPainter p
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t r
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize id
char name[80]
Definition TGX11.cxx:110
R__EXTERN TVirtualMutex * gInterpreterMutex
R__EXTERN TInterpreter * gCling
Int_t gDebug
Definition TROOT.cxx:622
R__EXTERN TVirtualMutex * gROOTMutex
Definition TROOT.h:63
#define gROOT
Definition TROOT.h:414
R__EXTERN TSystem * gSystem
Definition TSystem.h:572
R__EXTERN TThreadFactory * gThreadFactory
R__EXTERN void **(* gThreadTsd)(void *, Int_t)
static TMutex * gMainInternalMutex
Definition TThread.cxx:58
static void ThreadInternalUnLock()
Definition TThread.cxx:61
static void CINT_alloc_lock()
Definition TThread.cxx:55
static TThreadTearDownGuard gTearDownGuard
Definition TThread.cxx:91
static Bool_t fgIsTearDown(kFALSE)
static void ThreadInternalLock()
Definition TThread.cxx:60
void ROOT_TThread_Initialize()
Definition TThread.cxx:65
static void CINT_alloc_unlock()
Definition TThread.cxx:56
R__EXTERN TVirtualMutex * gGlobalMutex
#define R__LOCKGUARD(mutex)
R__EXTERN Int_t(* gThreadXAR)(const char *xact, Int_t nb, void **ar, Int_t *iret)
#define va_(arg)
Definition Varargs.h:35
#define snprintf
Definition civetweb.c:1540
Bool_t IsRunning() const
Int_t TimedWaitRelative(ULong_t ms)
Wait to be signaled or till the timer times out.
virtual void SetAllocunlockfunc(void(*)()) const
static TInterpreter * Instance()
returns gInterpreter global
TJoinHelper(TThread *th, void **ret)
Constructor of Thread helper class.
Definition TThread.cxx:117
TMutex * fM
Definition TThread.cxx:101
Int_t Join()
Thread join function.
Definition TThread.cxx:157
Bool_t fJoined
Definition TThread.cxx:103
Long_t fRc
Definition TThread.cxx:100
TThread * fH
Definition TThread.cxx:98
void ** fRet
Definition TThread.cxx:99
~TJoinHelper()
Destructor.
Definition TThread.cxx:126
TCondition * fC
Definition TThread.cxx:102
static void * JoinFunc(void *p)
Static method which runs in a separate thread to handle thread joins without blocking the main thread...
Definition TThread.cxx:138
TThread * fT
Definition TThread.cxx:97
Method or function calling interface.
Definition TMethodCall.h:37
Int_t UnLock() override
Unlock the mutex.
Definition TMutex.cxx:68
Int_t Lock() override
Lock the mutex.
Definition TMutex.cxx:46
The TNamed class is the base class for all named ROOT classes.
Definition TNamed.h:29
const char * GetName() const override
Returns name of object.
Definition TNamed.h:49
virtual const char * GetName() const
Returns name of object.
Definition TObject.cxx:457
virtual void Warning(const char *method, const char *msgfmt,...) const
Issue warning message.
Definition TObject.cxx:1057
virtual void Error(const char *method, const char *msgfmt,...) const
Issue error message.
Definition TObject.cxx:1071
virtual void Info(const char *method, const char *msgfmt,...) const
Issue info message.
Definition TObject.cxx:1045
Basic string class.
Definition TString.h:139
virtual void AddTimer(TTimer *t)
Add timer to list of system timers.
Definition TSystem.cxx:471
virtual void Sleep(UInt_t milliSec)
Sleep milliSec milli seconds.
Definition TSystem.cxx:437
virtual Bool_t ProcessEvents()
Process pending events (GUI, timers, sockets).
Definition TSystem.cxx:416
virtual const char * GetError()
Return system error string.
Definition TSystem.cxx:254
~TThreadCleaner()
Call user clean up routines.
Definition TThread.cxx:1225
virtual TThreadImp * CreateThreadImp()=0
Bool_t Notify() override
Periodically execute the TThread::XAction() method in the main thread.
Definition TThread.cxx:1207
TThreadTimer(Long_t ms=kItimerResolution+10)
Create thread timer.
Definition TThread.cxx:1199
<div class="legacybox"><h2>Legacy Code</h2> TThread is a legacy interface: there will be no bug fixes...
Definition TThread.h:40
VoidRtnFunc_t fFcnRetn
Definition TThread.h:84
static TThread * GetThread(Long_t id)
Static method to find a thread by id.
Definition TThread.cxx:466
static Int_t CleanUpPop(Int_t exe=0)
Static method which pops thread cleanup method off stack.
Definition TThread.cxx:701
static Int_t CancelPoint()
Static method to set a cancellation point.
Definition TThread.cxx:680
static Int_t Sleep(ULong_t secs, ULong_t nanos=0)
Static method to sleep the calling thread.
Definition TThread.cxx:754
static void **volatile fgXArr
Definition TThread.h:92
static Int_t CleanUpPush(void *free, void *arg=nullptr)
Static method which pushes thread cleanup method on stack.
Definition TThread.cxx:689
static Int_t TryLock()
Static method to try to lock the main thread mutex.
Definition TThread.cxx:784
void SetPriority(EPriority pri)
Set thread priority.
Definition TThread.cxx:458
static Int_t Exists()
Static method to check if threads exist.
Definition TThread.cxx:442
TThread * fPrev
Definition TThread.h:75
static void Ps()
Static method listing the existing threads.
Definition TThread.cxx:847
static void ** GetTls(Int_t k)
Static method that initializes the TLS array of a thread and returns the reference to a given positio...
Definition TThread.cxx:911
static TThreadImp * fgThreadImp
Definition TThread.h:90
static Int_t UnLock()
Static method to unlock the main thread mutex.
Definition TThread.cxx:792
Int_t Kill()
Kill this thread.
Definition TThread.cxx:594
static TMutex * fgMainMutex
Definition TThread.h:97
EState fState
Definition TThread.h:78
static volatile Int_t fgXAnb
Definition TThread.h:93
static Long_t fgMainId
Definition TThread.h:95
Long_t Join(void **ret=nullptr)
Join this thread.
Definition TThread.cxx:514
static void XAction()
Static method called via the thread timer to execute in the main thread certain commands.
Definition TThread.cxx:1078
virtual ~TThread()
Cleanup the thread.
Definition TThread.cxx:392
Bool_t fDetached
Definition TThread.h:82
static Int_t SetCancelAsynchronous()
Static method to set the cancellation response type of the calling thread to asynchronous,...
Definition TThread.cxx:661
static Int_t CleanUp()
Static method to cleanup the calling thread.
Definition TThread.cxx:712
void ErrorHandler(int level, const char *location, const char *fmt, va_list ap) const
Thread specific error handler function.
Definition TThread.cxx:959
static Int_t GetTime(ULong_t *absSec, ULong_t *absNanoSec)
Static method to get the current time.
Definition TThread.cxx:765
static Long_t SelfId()
Static method returning the id for the current thread.
Definition TThread.cxx:553
void Constructor()
Common thread constructor.
Definition TThread.cxx:364
static Int_t SetCancelOn()
Static method to turn on thread cancellation.
Definition TThread.cxx:651
static void ** Tsd(void *dflt, Int_t k)
Static method returning a pointer to thread specific data container of the calling thread.
Definition TThread.cxx:898
Long_t fId
Definition TThread.h:80
Bool_t fNamed
Definition TThread.h:83
Int_t Run(void *arg=nullptr, const int affinity=-1)
Start the thread.
Definition TThread.cxx:570
static volatile Int_t fgXArt
Definition TThread.h:94
void SetComment(const char *txt=nullptr)
Definition TThread.h:103
void DoError(Int_t level, const char *location, const char *fmt, va_list va) const override
Interface to ErrorHandler.
Definition TThread.cxx:1005
static Int_t XARequest(const char *xact, Int_t nb, void **ar, Int_t *iret)
Static method used to allow commands to be executed by the main thread.
Definition TThread.cxx:1028
static std::atomic< char * > volatile fgXAct
Definition TThread.h:48
VoidFunc_t fFcnVoid
Definition TThread.h:85
static void * Function(void *ptr)
Static method which is called by the system thread function and which in turn calls the actual user f...
Definition TThread.cxx:801
EPriority fPriority
Definition TThread.h:77
static void Printf(const char *fmt,...)
Static method providing a thread safe printf. Appends a newline.
Definition TThread.cxx:920
static Int_t Lock()
Static method to lock the main thread mutex.
Definition TThread.cxx:776
@ kRunningState
Definition TThread.h:64
@ kNewState
Definition TThread.h:63
@ kCanceledState
Definition TThread.h:69
@ kCancelingState
Definition TThread.h:68
@ kFinishedState
Definition TThread.h:67
@ kTerminatedState
Definition TThread.h:65
@ kDeletingState
Definition TThread.h:70
@ kInvalidState
Definition TThread.h:62
friend class TThreadTimer
Definition TThread.h:44
static Int_t SetCancelOff()
Static method to turn off thread cancellation.
Definition TThread.cxx:642
static void Init()
Initialize global state and variables once.
Definition TThread.cxx:319
static Int_t SetCancelDeferred()
Static method to set the cancellation response type of the calling thread to deferred,...
Definition TThread.cxx:671
Longptr_t fHandle
Definition TThread.h:81
static void AfterCancel(TThread *th)
Static method which is called after the thread has been canceled.
Definition TThread.cxx:733
static TThread * fgMain
Definition TThread.h:96
static TMutex * fgXActMutex
Definition TThread.h:98
EPriority
Definition TThread.h:55
@ kNormalPriority
Definition TThread.h:57
static Bool_t IsInitialized()
Return true, if the TThread objects have been initialize.
Definition TThread.cxx:309
static TThread * Self()
Static method returning pointer to current thread.
Definition TThread.cxx:498
static Int_t Exit(void *ret=nullptr)
Static method which terminates the execution of the calling thread.
Definition TThread.cxx:746
static void Initialize()
Initialize the Thread package.
Definition TThread.cxx:300
void * fClean
Definition TThread.h:87
static TCondition * fgXActCondi
Definition TThread.h:99
TThread(const TThread &)=delete
TThread ** fHolder
Definition TThread.h:76
TThread * fNext
Definition TThread.h:74
void Delete(Option_t *option="") override
Delete this object.
Definition TThread.h:127
void * fThreadArg
Definition TThread.h:86
The TTimeStamp encapsulates seconds and ns since EPOCH.
Definition TTimeStamp.h:45
time_t GetSec() const
Definition TTimeStamp.h:109
Int_t GetNanoSec() const
Definition TTimeStamp.h:110
Handles synchronous and a-synchronous timer events.
Definition TTimer.h:51
void Reset()
Reset the timer.
Definition TTimer.cxx:163
This class implements a mutex interface.
virtual Int_t UnLock()=0
virtual Int_t Lock()=0
TVirtualPad is an abstract base class for the Pad and Canvas classes.
Definition TVirtualPad.h:51
std::ostream & Info()
Definition hadd.cxx:177
const Int_t n
Definition legend1.C:16
R__EXTERN TVirtualRWMutex * gCoreMutex
@ kMaxThreadSlot
TROOT * GetROOT()
Definition TROOT.cxx:472
TMarker m
Definition textangle.C:8
TLine l
Definition textangle.C:4