Event level parallelism in Geant4 Version 10.0

Geant4 Version 10.0 event-level parallelism is based on a master-worker model in which a set of threads (the workers) are spawned and are responsible for the simulation the events, while an additional control thread (the master, in the simple cases the main application thread) is responsible of controlling the workers.
Multithreading functionalities are implemented with new classes or modification to existing classes in the run category:
  • The new run-manager class G4MTRunManager (that inherits from G4RunManager) implements the master model. It uses the mandatory class G4MTRunManagerKernel the multi-threaded equivalent of G4RunManagerKernel.
  • The new run-manager class G4WorkerRunManager (that inherits from G4WorkerRunManager) implements the worker model. It uses the mandatory class G4WorkerRunManagerKernel the worker-model equivalent of G4RunManagerKernel
  • The new user-initialization class G4VUserActionInitialization is responsible for the instantiation of thread-local user actions
  • The new user-initialization class G4UserWorkerInitialization is responsible for the initialization of worker threads
Additional information on Geant4 multi-threading model can be found here: Geant4MTAdvandedTopicsForApplicationDevelopers .

In this page we will concentrate on aspects that are important for kernel developers, in particular we will discuss the most critical aspect for Geant4 Version 10.0 multi-threading: memory handling, split-classes and thread-local storage.
A beginner guide to multi-threading targeted to Geant4 developers has been presented during the 18th Collaboration Meeting: https://indico.cern.ch/getFile.py/access?contribId=3&sessionId=7&resId=0&materialId=slides&confId=250021

Memory handling in Geant4 Version 10.0

Introduction

In Geant4 we distinguish two broad types of classes: ones whose instances are separate for each thread (such as a physics process, which has a state), and ones whose instances are shared between threads (e.g. an element G4Element which holds constant data ).

In a few cases classes exist which are split - part of their state is constant, and part is per-worker. A simple example of this is a particle definitions, such as G4Electron, which holds both data (which is constant) and a pointer to the G4ProcessManager object for electrons - which must be different for each worker (thread).

We handle these 'split' classes specially, to enable data members and methods which correspond to the per-thread state to give a different result on each worker thread. The implementation of this requires an array for each worker (thread) and an additional indirection - which imposes a cost for each time the method is called. However this overhead is small and has been measured to be about 1%.

Thread safety and sharing of objects

To better understand how memory is handled and what are the issues introduced by multi-threading it is easier to proceed with a simplified example.

Let us consider the simplest possible class G4Class that consists of a single data member:

class G4Class {
    [static] G4double fValue; //static keyword is optional
};
Our goal is to transform the code of G4Class to make it thread-safe. A class (or better, a method of a class) is thread-safe if more than one thread can simultaneously operate on the class data member of methods without interfering with each other in an unpredictable way. For example if two threads concurrently write and read the value of the data field fValue and this data field is shared among threads, the two threads can interfere with each other. This condition is called data-race and is particular dangerous and difficult to debug.

A classical way to solve this problem is to protect concurrent access to a shared memory location using a lock or a mutex (see section Threading model utilities and functions. However this technique can reduce overall performances because only one thread at a time is allowed to be executed. In Geant4 Version 10.0 we have achieved thread safety via the use of thread local storage. For an explanation of what is thread local storage several sources exists, for a basic introduction adequate for our discussion, web resources give enough details (e.g. wikipedia).

We define an instance of a variable thread-local (or thread-private) if each thread owns a copy of the variable. A thread-shared variable is an instance of a variable that is shared among the threads (i.e. all thread access to the same memory location that holds the value of the variable). In addition, if we need to share the same fValue between several instances of G4Class we call the data field instance-shared otherwise it is instance-local.

It is clear that, for the case of thread-shared variables, all thread needs synchronization to avoid race condition (it is worth to remind that there are no race conditions if the variable is accessed only to be read, for example in the case the variable is marked as const).

One or more instances of G4Class can exist in our application. These instances can be thread-local (e.g. G4VProcess) or thread-shared (e.g. G4LogicalVolume). In addition the class data field fValue can be by itself thread-local or thread-shared. The actions to be taken to transform the code depend on three key aspects:

  • Do we need to make the instance(s) of G4Class thread-local or thread-shared?
  • Do we need to make the data field fValue thread-local or thread-shared?
  • In case more than one instance of G4Class exits at the same time, do we need fValue to be instance-local or instance-shared?
This gives rise to 8 different possible combinations, summarized in the following figures:


Case A: thread-local class instance(s), thread-shared and instance-shared data field

In this case each thread has its own instance(s) of G4Class. We need to share fValue both among threads and among instances. As for a sequential application, we can simply add the static keyword to the declaration of fValue. This technique is common in Geant4 but has the disadvantage that the result code is thread-unsafe (unless locks are used). Trying to add const or modify its value (with the use of a lock) only outside of the event loop is the simplest and best solution:
class G4Class {
    static const G4double fValue;
};

Case B: thread-local class instance(s), thread-local and instance-shared data field.

This scenario is also common in Geant4: we need to share a variable (e.g. a data table) between instances of the same class. However it is impractical or would lead to wrong results if we share among threads fValue (e.g. large penalty due to the need of locks would be introduced or the data field holds a event-dependent information). To make the code thread-safe we mark the data field thread-local:
#include "G4Types.hh"
class G4Class {
    static G4ThreadLocal G4double fValue;
};
It should be noted that only simple data types can be declared G4ThreadLocal. More information and the procedure to make an object instance G4ThreadLocal is explained in here.

Case C: thread-local class instance(s), thread-shared and instance-local data field

This is probably the less frequent scenario. A possible use-case is the reduction of application memory footprint, providing a component to the thread-local instances of G4Class that is shared among threads (e.g. a large cross-section data table). Since this scenario strongly depends on the implementation details it is not possible to define a common strategy that guarantee thread-safety. The best one being to try to make this shared component const.

Case D: thread-local class instance(s), thread-local and instance-local data field

This case is the simplest, nothing has to be changed in the original code.

Case E: thread-shared class instance(s), thread-shared and instance-shared data field

This case is equivalent to Case A, and the same recommendations and comments are valid.

Case F: thread-shared class instance(s), thread-local and instance-shared data field

This case is equivalent to Case B, and the same recommendations and comments are valid.

Case G: thread-shared class instance(s), thread-shared and instance-shared data field

Since the class instances are shared among threads the data field are automatically thread-shared. No action is needed, however access to data field is not, in general thread safe, and the same comments as for Case A are valid.

Case H: thread-sahred class instance(s), thread-local and instance-local data field

This is the most complex case and it is relatively common in Geant4 Version 10.0. For example G4ParticleDefinition instances are shared among the threads, but the G4ProcessManager needs to be thread and instance local. To obtain thread-safe code two possible solutions exists:
  • Use the split-class mechanism. This requires some deep understanding of Geant4 multi-threading and coordination with the kernel developers. Split-classes result in thread-safe code with good CPU performances, however they also require modification in other aspects of kernel category (in particular they require changes in run category). The idea behind the split-class mechanism is that each thread-shared instance of G4Class initializes the thread-local data fields copying the initial status from the master thread, guaranteed to be fully configured. Additional details on split classes are available here.
  • If performances are not a concern a simpler solution is available. This is a simplified version of the split-class mechanism that does not copy the initial status of the thread-local data field from the master thread. A typical example is a cache variable that reduces CPU usage keeping in memory the value of a CPU intensive calculation. In such a case the G4Cache utility class can be employed (see here).

Details on the split classes mechanism

Let's consider again our simplified example:
class G4Class
{
 private:
    G4double fValue;
 public:
    G4Class() {  }
    void SetMyData( G4double aValue ) { fValue = aValue; }
    G4double GetMyData() const { return fValue; }
};
We want to transform this class to a split-class.

At first we can add to the declaration of fValue the TLS keyword G4ThreadLocal. Unfortunately there are several constraints on what can be specified as TLS (G4ThreadLocal in a POSIX system is a typedef to __thread), in particular the data member has to be declared static:

#include "tls.hh"
class G4Class 
{
 private:
    static G4ThreadLocal G4double fValue;
 public:
    G4Class()  {  }
    void SetMyData( G4double aValue ) { fValue = aValue; }
    G4double GetMyData() const { return fValue; }
};
G4ThreadLocal G4double G4Class::fValue = -1; 
The problem occurs if you need more than one instance of objects of type G4Class each one with a different value of fValue. How to obtain this behavior now that the data member is static? The method used to solve this problem is called split class mechanism. The idea is to collect all per-thread objects into a separate class, instances of which are organized in an array, that is accessed via a index representing a unique identifier of a given class instance. Continuing with our example, let's assume we create several instances of G4Class (e.g. G4LogicalVolume or G4ParticleDefinition).

We can modify the code as follow:

class G4ClassData {
public:
   G4double fValue;
   void intialize() {
           fValue = -1;
   }
};

typedef G4Splitter<G4ClassData> G4ClassManager;
typedef G4ClassManager G4ClassSubInstanceManager;

#define G4MT_fValue ((subInstanceManager.offset[gClassInstanceId]).fValue)
class G4Class {
private: 
    G4int gClassInstanceId;
    static G4ClassSubInstanceManager subInstanceManager;
public:
    G4Class()
   { 
      gClassInstanceId = subInstanceManager.CreateSubInstance();
    }
    void SetMyData( G4double aValue ) { G4MT_fValue = aValue; }
    G4double GetMyData() const { return G4MT_fValue; }
};

G4ClassSubInstanceManager G4Class::subInstanceManager;
template <class G4ClassData> G4ThreadLocal G4int G4Splitter<G4ClassData>::workertotalspace = 0;
template <class G4ClassData> G4ThreadLocal G4int G4Splitter<G4ClassData>::offset = 0;

As one can see the use of the value of fValue variable is very similar to how we use it in the original sequential mode, all the handling of the TLS is done in the template class G4Splitter that can be implemented as:

template <class T>
class G4Splitter
{
  private:
    G4int totalobj;
  public:
    static G4ThreadLocal G4int workertotalspace;
    static G4ThreadLocal T* offset;
  public:
    G4Splitter() : totalobj(0) {}
    G4int CreateSubInstance() 
    {
       totalobj++;
       if ( totalobj > workertotalspace ) { NewSubInstances(); }
       return (totalobj-1); 
    }
    void NewSubInstances()
    {
         if ( workertotalspace >=totalobj ) { return; }
         G4int originaltotalspace = workertotalspace;
         workertotalspace = totalobj + 512;
         offset = (T*) realloc( offset , workertotalspace * sizeof(T) );
         if ( offset == 0 ) 
         { 
            G4Excepetion( "G4Splitter::NewSubInstances","OutOfMemory",FatalException,"Cannot malloc space!");
         }
        for ( G4int i = originaltotalspace; i < workertotalspace ; i++)
        {
            offset[i].intialize();
        }
    }
   void FreeWorker()
   {
     if ( offset == 0 ) { return; }
     delete offset;
   }
};

Let's Imagine now a function that can be called concurrently by more than one thread:

#include "G4Class.hh"
//Variables at global scope
G4Class a; 
G4Class b;

void foo() 
{
     a.SetMyData(0.1); //First instance
     b.SetMyData(0.2); //Second instance
   G4cout<< a.GetMyData() << " "<< b.GetMyData() << G4endl;
}
We expect that each thread will write on screen: "0.1 0.2" Here is how it works:
When we declare the variable a, the static object subInstanceManager in memory has a state:
totalobj = 0
TLS workertotalspace = 0 
TLS offset = NULL (remember this is a pointer!)
The constructor of G4Class calls CreateSubInstance, and since now totalobj equals 1, G4Splitter::NewSubInstances() is called. This will create a (new) buffer of 512 pointers of type G4ClassData, each of them is initialized (via G4ClassData::initialize()) to the value -1. Finally, G4Splitter::CreateSubInstance() returns 0 and a.gClassInstanceId equals 0. When a.SetMyData(0.1) is called, the call is equivalent to:
subInstanceManager.offset[0].fValue = 0.1;
When now we declare the instance b the procedure is repeated, except that, since totalobj now equals 1 and workertotalspace is 512, there is no need to call G4Splitter::NewSubInstances() and we use the next available pointer position in offset. Only if we create more than 512 instances of G4Class we need to re-allocate new memory space for the G4ClassData objects.

Since offset and workertotalspace are G4ThreadLocal this mechanism allows each thread to have its own copy of fValue. The function foo() can be called from different threads and they will use the thread-shared a and b to access a thread-local fValue data field..

A realistic example of this can be seen in the class G4ParticleDefinition. An additional complication is when the initialization of the thread-local part is not trivial and we want to "copy" some values from the corresponding values of the master thread (in our example, how to initialize fValue to a default value at run time?). How to obtain this is shown in G4LogicalVolume, but it should be noted that the worker thread need to call a special function to initialize correctly the worker thread memory space. For this reason Geant4 kernel code needs to be adapted every time a new class is declared split.

The following diagram shows the chain of calls in G4ParticleDefinition when a thread needs to access a process pointer:

List of split-classes

In Geant4 Version 10.0 the following are split-classes:
  • For geometry related split classes the class G4GeomSplitter implements the split-class mechanism. These are the geometry related split-classes:
  1. G4LogicalVolume
  2. G4PhysicalVolume
  3. G4PVReplica
  4. G4Region
  5. G4PloyconeSide
  6. G4PolyhedraSide
  • For Physics related split-classes the classes G4PDefSplitter and G!4VUPLSplitter implement the split-class mechanism. These are the physics related split-classes:
  1. G4ParticleDefinition
  2. G4VUserPhysicsList
  3. G4VModularPhysicsList
  4. G4VPhysicsConstructor

Explicit memory handling

In the following some utility classes and functions to help the memory handling are discussed. Before going in the detail it should be noted that all of these utilities have a (small) CPU and memory performance penalty, they should be used with caution and only if other simpler methods are not possible. In some cases limitations are present.

G4Cache template class

As discussed in previous paragraph the split-class mechanism allows for an efficient implementation of many thread-shared instances with thread and instance local data field. This technique is efficient because it is based on the assumption that when worker threads start the thread-local part of the instances can be initialized, for each worker, copying from the fully initialized thread-local memory from master thread.

In many cases this is not needed and what we really want are independent thread-local and instance-local data field in thread-shared instances of G4Class. For example a class representing a cross-section is made shared because of its memory footprint. However it requires a data field to act as a cache to store a value of a CPU intensive calculation. Since different thread share this instance we need to transform the code in a manner similar to what we do for split-classes mechanism. The helper class G4Cache can be used for this purpose.

This is a template class that implements a light-weight split-classes mechanism. Being a template it allows for storing any user-defined type. The public API of this class is very simple and it provides two methods

T& G4Cache<T>::Get() const;
void G4Cache<T>::Put(const T& val) const;
to access a thread-local instance of the cached object.

#include "G4Cache.hh"
class G4Class {
    G4Cache<G4double> fValue;
    void foo() {
          // Store a thread-local value
          G4double val = someHeavyCalc();
          fValue.Put( val );
    }
    void bar() {
         //Get a thread-local value:
         G4double local = fValue.Get();
    }
};
Since Get returns a reference to the cached object is possible to avoid to use Put to update the cache:
void G4Class::bar() {
    //Get a reference to the thread-local value:
   G4double& local = fValue.Get();
   // Use local as in the original sequential code, cache is updated, without the need to use Put
  local++;
}
In case the cache holds a instance of an object it is possible to implement a lazy initialization, as in the following example:
#include "G4Cache.hh"
class G4Class {
    G4Cache<G4Something*> fValue;
    void bar() {
         //Get a thread-local value:
         G4Something* local = fValue.Get();
         if ( local == 0 ) {
                   local = new G4Something( . );
                   //warning this may cause a memory leak. Use of G4AutoDelete can help, see later
         }
    }
};

The use of G4Cache implies some CPU penalty, it is a good practice to try to minimize the use of G4Cache. For example, do not use them in several data field separately, but use a helper structure and use this structure as template parameter:

class G4Class {
   struct {
       G4double fValue1;
       G4Something* fValue2;
   } ToBeCached_t;
  G4Cache&ltToBeCached_t&gt fCache;
};

Finally two specialized versions of G4Cache exist that implement the semantics of std::vector and std::map:

  • G4VectorCache<T> implements thread-local std::vector<T> = with methods: =Push_back() , operator[], Begin(), End(), Clear(), Size(), Pop_back()
  • G4MapCache<K,V> implements thread-local std::map<K,V> with methods: Insert(), Begin(), End(), Find(), Size(), Get(), Erase(), operator[] and introduces the method Has()

G4AutoDelete namespace

In the previous discussion about G4Cache we have shown the example of using a pointer to a dynamically created object as the template parameter of G4Cache. A common problem is to correctly delete this object at the end of its lifecicle. Since the G4Class instance is shared among threads it is not possible to delete the cached object in the destructor, since the destructors is called by a single thread and thread-local instances of G4Something will not be deleted. To partially solve this problem it is possible to use a helper introduced in the namespace G4AutoDelete. This introduces a simplified garbage collection mechanism without reference counting. With reference to the previous example:
#include "G4AutoDelete.hh"
void G4Class::bar() {
    //Get a thread-local value:
    G4Something* local = fValue.Get();
    if ( local == 0 ) {
            local = new G4Something( . );
            G4AutoDelete::Register( local ); //All thread instances will be delete automatically
    }
}

This technique will delete all instances of the registered objects at the end of the program after the main function has returned (as they would have been declared static).

This method requires some attention and has several limitations: 1 Registered objects will be deleted only at the end of the program 1 The order in which objects of different type will be deleted is not specified 1 Once an object is registered it cannot be deleted anymore explicitly by user 1 The objects that are registered with this method cannot contain G4ThreadLocal data and cannot be split-classes 1 Registered object cannot make use of G4Allocator In particular since the objects will be deleted after the main program exit in a non-specified order their destructors should be simple and should not depend on other objects.

Thread Private singleton

In Geant4 the singleton pattern is used in several areas. The majority of managers are implemented via the singleton pattern, that in the most simple implementation is similar to:
class G4Singleton {
public:
   G4Singleton* GetInstance() {
        static G4Singleton anInstance;
        return &anInstance;
   }   
};

With multi-threading many managers and singletons are required to become thread-local. For this reason they have been transformed to:

class G4Singleton {
private:
   static G4ThreadLocal* instance;
public:
   G4Singleton* GetInstance() {
        if ( instance == 0 ) instance = new G4Singleton;
        return instance;
   }   
};

This causes a memory leak since it is not possible to delete thread-local instances of the singletons. The class G4ThreadLocalSingleton can be used to solve this problem. This template class has a single public method T* G4ThreadLocalSingleton<T>::Instance() that returns a pointer to a thread-local instance of T.

The example code can be transformed to:

#include "G4ThreadLocalSingleton.hh"
class G4Singleton {
   friend class G4ThreadLocalSingleton<G4Singleton>;
public:
   G4Singleton* GetInstance() {
       static G4ThreadLocalSingleton<G4Singleton> theInstance; 
       return theInstance.Instance();
   }   
};

Threading model utilities and functions

Geant4 parallelism is based on POSIX standards and in particular on the pthreads library. However all functionalities have been wrapped around Geant4 specific names. This will allow to include WIN32 threading model. In the following a list of the main functionalities available in global/management category are discussed.

Thread related types and functions.

G4Thread defined the type for threads (POSIX pthread_t), and the corresponding G4ThreadFunReturnType, G4ThreadFunArgType respectively define return value and argument type for a function to be executed in a thread. Use G4THREADCREATE and G4THREADJOIN functions to create and join a thread. G4Pid_t is the type for the PID of a thread.

Example:

//Define a thread-function using G4 types
G4ThreadFunReturnType myfunc(  G4ThreadFunArgType val) {
  double value = *(double*)val;
  MESSAGE("value is:"<<value);
  return /*(G4ThreadFunReturnType)*/NULL;
}

//Example: spawn 10 threads that execute myfunc
int main(int,char**) {
  MESSAGE( "Starting program ");
  int nthreads = 10;
  G4Thread* tid = new G4Thread[nthreads];
  double *valss = new double[nthreads];
  for ( int idx = 0 ; idx < nthreads ; ++idx ) {
    valss[idx] = (double)idx;
    G4THREADCREATE( &(tid[idx]) , myfunc, &(valss[idx]) );
  }
  for ( int idx = 0 ; idx < nthreads ; ++idx ) {
    G4THREADJOIN( (tid[idx]) );
  }
  MESSAGE( "Program ended ");
  return 0;
}

Mutex/conditions related types and functions

G4Mutex is the type for mutexes (POSIX pthread_mutex_t), with G4MUTEX_INITIALIZER macro and G4MUTEXINIT function used to initialize a mutex. Use G4MUTEXLOCK and G4MUTEXUNLOCK functions to lock/unlock a mutex. G4AutoLock class helps the handling of auto-unlock mutex and should be always be used instead of G G4MUTEXLOCK/UNLOCK.

Example:

//Create a global mutex
G4Mutex mutex = G4MUTEX_INITIALIZER; //Alternatively, call G4MUTEXINIT(mutex);

//A shared resource (e.g. manipulated by all threads)
G4int aValue = 1;

G4ThreadFunReturnType myfunc(  G4ThreadFunArgType ) {
  //Explicit lock/unlock
  G4MUTEXLOCK( &mutex );
  ++aValue;
  G4MUTEXUNLOCK( &mutex );
  //The following should be used instead of the previous because it guarantees automatic
  //unlock of mutex.
  //When variable l goes out of scope, G4MUTEXUNLOCK is automatically called
  G4AtuoLock l(&mutex);
  --aValue;
  //Explicit lock/unlock. Note that lock/unlock is not tried if already locked/unlock
  l.lock();
  l.lock();//No problem here
  ++aValue;
  l.unlock();
  l.lock();
  --aValue;
  return /*(G4ThreadFunReturnType)*/NULL;
}

Conditions are also available via the G4Condition type, G4CONDITION_INITIALIZER macro and the two functions G4CONDITIONWAIT and G4CONDITIONBORADCAST. The use of condition allows to implement the barrier mechanism (e.g. synchronization point for threads). A detailed example on the use of condition and how to implement correctly a barrier is discussed in G4MTRunManager code (at the end of file source/run/src/G4MTRunManager.cc).

Additional material

For additional information consult this page Geant4MTAdvandedTopicsForApplicationDevelopers
and this page Geant4MTTipsAndTricks
Several contribution at the 18th Collaboration Meeting discuss multi-threading: Plenary Session 3 - Geant4 version 10 (part 1)
Parallel session 7B - Hadronics issues related to MT
Developments for multi-threading: work-spaces
Status of the planned developments: coding guidelines, MT migration, g4tools migration, code review
G4MT CP on MIC Architecture Articles:
  • X. Dong et al, Creating and Improving Multi-Threaded Geant4 , Journal of Physics: Conference Series 396, no. 5, p. 052029.
  • X. Dong et al, Multithreaded Geant4: Semi-automatic Transformation into Scalable Thread-Parallel Software, Euro-Par 2010 - Parallel Pro- cessing (2010), vol. 6272, pp. 287-303.
  • S. Ahn et al, Geant4-MT: bringing multi-threaded Geant4 into production, to be published in SAN&MC2013 proceeding
Topic attachments
I Attachment History Action Size Date Who Comment
JPEGjpg SplitClassSimple.jpg r1 manage 167.6 K 2013-12-05 - 21:32 AndreaDotti  
JPEGjpg SplitClasses-MemHandling.001.jpg r1 manage 178.5 K 2013-12-05 - 00:37 AndreaDotti  
JPEGjpg SplitClasses-MemHandling.002.jpg r1 manage 193.8 K 2013-12-05 - 00:37 AndreaDotti  
Edit | Attach | Watch | Print version | History: r9 < r8 < r7 < r6 < r5 | Backlinks | Raw View | WYSIWYG | More topic actions
Topic revision: r9 - 2013-12-05 - AndreaDotti
 
    • Cern Search Icon Cern Search
    • TWiki Search Icon TWiki Search
    • Google Search Icon Google Search

    Geant4 All webs login

This site is powered by the TWiki collaboration platform Powered by PerlCopyright & 2008-2020 by the contributing authors. All material on this collaboration platform is the property of the contributing authors.
Ideas, requests, problems regarding TWiki? Send feedback