Reputation: 2051
I have 3 function and 4 cores. I want execute each function in new thread using MPI and C++ I write this
int rank, size;
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD,&rank);
MPI_Comm_size(MPI_COMM_WORLD,&size);
size--;
if (rank == 0)
{
Thread1();
}
else
{
if(rank == 1)
{
Thread2();
}
else
{
Thread3();
}
}
MPI_Finalize();
But it execute just Thread1(). How i must change code?
Thanks!
Upvotes: 2
Views: 1228
Reputation: 8391
Print to screen the current value of variable size
(possibly without decrementing it) and you will find 1
. That is: "there is 1
process running".
You are likely running your compiled code the wrong way. Consider to use mpirun
(or mpiexec
, depending on your MPI implementation) to execute it, i.e.
mpirun -np 4 ./MyCompiledCode
the -np
parameter specifies the number of processes you will start (doing so, your MPI_Comm_size
will be 4 as you expect).
Currently, though, you are not using anything explicitly owing to C++. You can consider some C++ binding of MPI such as Boost.MPI
.
I worked a little bit on the code you provided. I changed it a little bit producing this working mpi code (I provided some needed correction in capital letters).
FYI:
compilation (under gcc, mpich):
$ mpicxx -c mpi1.cpp
$ mpicxx -o mpi1 mpi1.o
execution
$ mpirun -np 4 ./mpi1
output
size is 4
size is 4
size is 4
2 function started.
thread2
3 function started.
thread3
3 function ended.
2 function ended.
size is 4
1 function started.
thread1
1 function ended.
be aware that stdout
is likely messed out.
Are you sure you are compiling your code the right way?
Upvotes: 6
Reputation: 74355
You problem is that MPI provides no way to feed console input into many processes but only into process with rank 0
. Because of the first three lines in main
:
int main(int argc, char *argv[]){
int oper;
std::cout << "Enter Size:";
std::cin >> oper; // <------- The problem is right here
Operations* operations = new Operations(oper);
int rank, size;
MPI_Init(&argc, &argv);
int tid;
MPI_Comm_rank(MPI_COMM_WORLD, &tid);
switch(tid)
{
all processes but rank 0
block waiting for console input which they cannot get. You should rewrite the beginning of your main
function as follows:
int main(int argc, char *argv[]){
int oper;
MPI_Init(&argc, &argv);
int tid;
MPI_Comm_rank(MPI_COMM_WORLD, &tid);
if (tid == 0) {
std::cout << "Enter Size:";
std::cin >> oper;
}
MPI_Bcast(&oper, 1, MPI_INT, 0, MPI_COMM_WORLD);
Operations* operations = new Operations(oper);
switch(tid)
{
It works as follows: only rank 0
displays the prompt and then reads the console input into oper
. Then a broadcast of the value of oper
from rank 0
is performed so all other processes obtain the correct value, create the Operations
object and then branch to the appropriate function.
Upvotes: 2