2
我想用MPI編寫一個簡單的程序,它找到所有小於514的數字,它們等於它們數字之和的指數(例如,512 =(5 + 1 + 2 )^ 3。我遇到的問題是主循環 - 它在幾次迭代(c = 10)時工作得很好,但是當我嘗試增加迭代次數(c = x)時,mpiexec.exe只是掛起 - 。看似MPI在執行期間掛起
的printf例行中旬,我敢肯定,死鎖是罪魁禍首,但我找不到任何
的源代碼:
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include "mpi.h"
int main(int argc, char* argv[])
{
//our number
int x=514;
//amount of iterations
int c = 10;
//tags for message identification
int tag = 42;
int tagnumber = 43;
int np, me, y1, y2;
MPI_Status status;
/* Initialize MPI */
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &np);
MPI_Comm_rank(MPI_COMM_WORLD, &me);
/* Check that we run on more than two processors */
if (np < 2)
{
printf("You have to use at least 2 processes to run this program\n");
MPI_Finalize();
exit(0);
}
//begin iterations
while(c>0)
{
//if main thread, then send messages to all created threads
if (me == 0)
{
printf("Amount of threads: %d\n", np);
int b = 1;
while(b<np)
{
int q = x-b;
//sends a number to a secondary thread
MPI_Send(&q, 1, MPI_INT, b, tagnumber, MPI_COMM_WORLD);
printf("Process %d sending to process %d, value: %d\n", me, b, q);
//get a number from secondary thread
MPI_Recv(&y2, 1, MPI_INT, b, tag, MPI_COMM_WORLD, &status);
printf ("Process %d received value %d\n", me, y2);
//compare it with the sent one
if (q==y2)
{
//if they're equal, then print the result
printf("\nValue found: %d\n", q);
}
b++;
}
x = x-b+1;
b = 1;
}
else
{
//if not a main thread, then process the message sent and send the result back.
MPI_Recv (&y1, 1, MPI_INT, 0, tagnumber, MPI_COMM_WORLD, &status);
int sum = 0;
int y2 = y1;
while (y1!=0)
{
//find the number's sum of digits
sum += y1%10;
y1 /= 10;
}
int sum2 = sum;
while(sum2<y2)
{
//calculate the exponentiation
sum2 = sum2*sum;
}
MPI_Send (&sum2, 1, MPI_INT, 0, tag, MPI_COMM_WORLD);
}
c--;
}
MPI_Finalize();
exit(0);
}
然後我運行編譯的exe文件爲「mpiexec.exe -n 4 lab2.exe」。我使用HPC Pack 2008 SDK,如果這對您有任何用處。
有什麼方法可以解決它嗎?或者,也許某種方式來正確調試這種情況?
非常感謝!
其實,是的,這是問題所在。程序試圖找到一個數字的總和(比如說,「1000」),計算sum2 = 1 + 0 + 0 + 0 = 1,然後卡在1 = 1 * 1。非常感謝你指出這一點=)你是我的英雄。 – user2421911