2011-06-28 63 views
0

這個程序演示了一個不安全的程序,因爲它有時會執行正常,有時會失敗。程序失敗或掛起的原因是由於接收任務端的緩衝區耗盡,這是MPI庫爲特定大小的消息實現了預先協議的結果。一種可能的解決方案是在發送和接收循環中都包含一個MPI_Barrier調用。如何解決這個MPI代碼程序

它的程序代碼是否正確?

#include "mpi.h" 
#include <stdio.h> 
#include <stdlib.h> 

#define MSGSIZE 2000 

int main (int argc, char *argv[]) 
{ 
int  numtasks, rank, i, tag=111, dest=1, source=0, count=0; 
char  data[MSGSIZE]; 
double  start, end, result; 
MPI_Status status; 

MPI_Init(&argc,&argv); 
MPI_Comm_size(MPI_COMM_WORLD, &numtasks); 
MPI_Comm_rank(MPI_COMM_WORLD, &rank); 

if (rank == 0) { 
    printf ("mpi_bug5 has started...\n"); 
    if (numtasks > 2) 
    printf("INFO: Number of tasks= %d. Only using 2 tasks.\n", numtasks); 
    } 

/******************************* Send task **********************************/ 
if (rank == 0) { 

    /* Initialize send data */ 
    for(i=0; i<MSGSIZE; i++) 
    data[i] = 'x'; 

    start = MPI_Wtime(); 
    while (1) { 
    MPI_Send(data, MSGSIZE, MPI_BYTE, dest, tag, MPI_COMM_WORLD); 
    count++; 
    if (count % 10 == 0) { 
     end = MPI_Wtime(); 
     printf("Count= %d Time= %f sec.\n", count, end-start); 
     start = MPI_Wtime(); 
     } 
    } 
    } 

/****************************** Receive task ********************************/ 

if (rank == 1) { 
    while (1) { 
    MPI_Recv(data, MSGSIZE, MPI_BYTE, source, tag, MPI_COMM_WORLD, &status); 
    /* Do some work - at least more than the send task */ 
    result = 0.0; 
    for (i=0; i < 1000000; i++) 
     result = result + (double)random(); 
    } 
    } 

MPI_Finalize(); 
} 
+0

請正確格式化您的代碼,請參閱[Meta](http://meta.stackexchange.com/questions/22186/how-do-i-format-my-code-blocks)。 – larsmoa

回答

1

如何改善這種代碼,使接收器不與無限數量的unexpected messages最終包括:

  • 同步 - 你提到MPI_Barrier,但即使使用MPI_Ssend代替MPI_SEND會工作。
  • 顯式緩衝 - 使用MPI_Bsend或Brecv來確保存在適當的緩衝。
  • 發佈接收 - 接收過程在開始工作之前發佈IRecvs,以確保將消息接收到旨在容納數據的緩衝區中,而不是系統緩衝區中。

在這個教學案例中,由於消息的數量是無限的,所以只有第一個(同步)才能可靠地工作。

+0

謝謝先生.. 你能給我它的程序代碼行是否正確..! 請幫幫我! 謝謝 方面 – Jamalludin