XGCa
task_group.hpp
Go to the documentation of this file.
1 #ifndef TASK_GROUP_HPP
2 #define TASK_GROUP_HPP
3 #ifdef USE_MPI
4 #include "my_mpi.hpp"
5 #endif
6 
14 class TaskGroup{
15 #ifdef USE_MPI
16  MPI_Comm comm;
17 #endif
18  int my_rank;
19  int n_ranks;
20 
21  public:
22 
27  : my_rank(0),
28  n_ranks(1){}
29 
30 #ifdef USE_MPI
36  TaskGroup(MPI_Comm comm_in)
37  : comm(comm_in)
38  {
39  MPI_Comm_size( comm, &n_ranks );
40  MPI_Comm_rank( comm, &my_rank );
41  }
42 #endif
43 
49  int get_my_rank() const{
50  return my_rank;
51  }
52 
59  int get_n_local_tasks(int n_tasks) const{
60  return ((n_tasks + n_ranks - my_rank - 1)/n_ranks);
61  }
62 
69  int get_max_n_local_tasks(int n_tasks) const{
70  return ((n_tasks + n_ranks - 1)/n_ranks);
71  }
72 
73 #ifdef USE_MPI
74  MPI_Comm get_comm() const{
75  return comm;
76  }
77 #endif
78 
86  template<typename F>
87  void execute_task(int ntasks, F func) const{
88  for(int itask=0; itask<ntasks; itask++){
89  int assigned_rank = itask%n_ranks;
90  if(my_rank==assigned_rank){
91  int i_local_task = itask/n_ranks;
92  func(itask, i_local_task);
93  }
94  }
95  }
96 
97 #ifdef USE_MPI
105  template<typename F>
106  void communicate(int ntasks, F func) const{
107  for(int itask=0; itask<ntasks; itask++){
108  int i_local_task = itask/n_ranks;
109  int assigned_rank = itask%n_ranks;
110  bool is_assigned_rank = (my_rank==assigned_rank);
111  func(itask, i_local_task, assigned_rank, is_assigned_rank, comm);
112  }
113  }
114 #endif
115 };
116 
117 #endif
A class that manages the distribution and execution of tasks in parallel using the MPI library....
Definition: task_group.hpp:14
int my_rank
The rank of the current process within the MPI communicator.
Definition: task_group.hpp:18
int get_my_rank() const
Get the rank of the current process within the MPI communicator.
Definition: task_group.hpp:49
TaskGroup()
Default constructor for the TaskGroup class.
Definition: task_group.hpp:26
void execute_task(int ntasks, F func) const
Execute the given task function for each assigned task.
Definition: task_group.hpp:87
int get_max_n_local_tasks(int n_tasks) const
Calculate the maximum number of tasks assigned to any process.
Definition: task_group.hpp:69
int get_n_local_tasks(int n_tasks) const
Calculate the number of tasks assigned to the current process.
Definition: task_group.hpp:59
int n_ranks
The total number of processes within the MPI communicator.
Definition: task_group.hpp:19