Logo ROOT   6.07/09
Reference Guide
threads.C
Go to the documentation of this file.
1 /// \file
2 /// \ingroup tutorial_thread
3 /// Example of a simple script creating 3 threads.
4 /// This script can only be executed via ACliC: .x threads.C++.
5 /// Before executing the script, load the Thread library with:
6 ///
7 /// ~~~{.cpp}
8 /// gSystem->Load("libThread");
9 /// ~~~
10 ///
11 /// This is not needed anymore due to the rootmap facility which
12 /// automatically loads the needed libraries.
13 ///
14 /// \macro_code
15 ///
16 /// \author Victor Perevovchikov
17 
18 #include "TThread.h"
19 #include <Riostream.h>
20 
21 void *handle(void *ptr)
22 {
23  long nr = (long) ptr;
24 
25  for (int i = 0; i < 10; i++) {
26  //TThread::Lock();
27  //printf("Here I am loop index: %3d , thread: %d\n",i,nr);
28  //TThread::UnLock();
29 
30  TThread::Printf("Here I am loop index: %d , thread: %ld", i, nr);
31  gSystem->Sleep(1000);
32  }
33  return 0;
34 }
35 
36 void threads()
37 {
38 
39  gDebug = 1;
40 
41  printf("Starting Thread 1\n");
42  TThread *h1 = new TThread("h1", handle, (void*) 1);
43  h1->Run();
44  printf("Starting Thread 2\n");
45  TThread *h2 = new TThread("h2", handle, (void*) 2);
46  h2->Run();
47  printf("Starting Thread 3\n");
48  TThread *h3 = new TThread("h3", handle, (void*) 3);
49  h3->Run();
50 
51  TThread::Ps();
52 
53  h1->Join();
54  TThread::Ps();
55  h2->Join();
56  h3->Join();
57  TThread::Ps();
58 }
static void Printf(const char *fmt,...)
Static method providing a thread safe printf. Appends a newline.
Definition: TThread.cxx:910
virtual void Sleep(UInt_t milliSec)
Sleep milliSec milli seconds.
Definition: TSystem.cxx:442
TH1F * h1
Definition: legend1.C:5
Int_t Run(void *arg=0)
Start the thread.
Definition: TThread.cxx:552
R__EXTERN TSystem * gSystem
Definition: TSystem.h:549
Long_t Join(void **ret=0)
Join this thread.
Definition: TThread.cxx:499
static void Ps()
Static method listing the existing threads.
Definition: TThread.cxx:829
R__EXTERN Int_t gDebug
Definition: Rtypes.h:128