Global Variables and MPI

I know that global variables are bad and should be avoided as much as possible. However, when writing parallel programs using MPI, some variables are only initialized once and never changed (the number of this task, the total number of tasks, etc.). Still considered bad practice to have these variables global? Since you largely need access to these variables all the time, it seems silly to make a class for them basically and pass a pointer to it for up to 99% of all functions in the program. So far, my approach has been to hide them in the mpi_glob namespace (for C ++, I think I would not put them in a C structure to emulate the namespace). I think the question also applies to other variables only once, for example, to a unit system, etc.

+5
source share
3 answers

The reason global variables are “bad” is because they introduce relationships between individual source files that are difficult to identify and track. In particular, if a global variable has an unexpected state at some point in the program, it can be difficult to determine where it was changed.

Replacing global variables with local variables that are passed by reference to each function in the program does not fix this problem. In terms of design, this is “vagabond data”, i.e. Data that wander around even where it is not needed.

, , , , , , , "". , .

+5

, , .

( /), , , "" . , . , - , :

using namespace mpi_glob;

, - .

, . , , .

0

, Singleton , . , mpi_glob , Singleton .

- . , const :

const int number_of_tasks = get_preconfigured_number_of_tasks();

, enum . , .


, . , .

, Java? , . Main -, .. ( Java, ).

We can further extend the concept to a Command- like implementation. The difference with regular Java is that your main equivalent of the method is not static, and your global variables with values ​​specific to the contained program are non-stationary member variables. All functions that need access to global state data must be converted to member functions. This is possible because the main function is also a member function.

Thus, I think you can achieve better sealing and data security.

0
source

All Articles