close

找了網路文章,總算解決為甚麼MPI_Barrier沒有發生作用

MPI_Barrier() 失效,不起作用,printf顺序不正确,解决方案。

 

Collective Communication

利用MPI_Barrier達到阻塞同步

換言之,先完成的processor需等待未完成的processor

#include <iostream>

 

#include <mpi.h>

 

#include <time.h>

 

#include <Windows.h>

 

void currentTime()

 

{

 

      SYSTEMTIME currentTime;

 

      GetSystemTime(&currentTime);

 

      printf("%u:%u:%u.%u ",

 

      currentTime.wHour + 8, currentTime.wMinute, currentTime.wSecond,

 

      currentTime.wMilliseconds, currentTime);

 

}
void CountNumbers(int rank, int n0, int n1)
{
     printf("\n");
     for (int i = n0; i <= n1; i++)
    {
        printf("%d: count number: %d\n", rank, i);
    }
    srand(time(NULL) + rank);
    long random_value = rand() % 5 + 1;
    printf("%d: sleeping %l secs: %d\n", rank, random_value);
    Sleep(1000 * random_value);
}
 
int main(int argc, char** argv)
{
    int rank, num_procs;
    MPI_Init(&argc, &argv);
    MPI_Comm_size(MPI_COMM_WORLD, &num_procs);
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);
    double t0, t1;
    /* (1)  數 1~5 */
    // 計時開始
    t0 = MPI_Wtime();
    // 數1~5
    CountNumbers(rank, 1, 5);
    t1 = MPI_Wtime();
    // 計算經過時間
    std::cout << (t1 - t0) << std::endl;
 
    // (障礙物)作為同步執行用,先執行完成的processor必須在此等待尚未執行完成的processor
    MPI_Barrier(MPI_COMM_WORLD);
 
    /* (2)  數 6~10 */
    // 計時開始
    t0 = MPI_Wtime();
 
    CountNumbers(rank, 6, 10);
    t1 = MPI_Wtime();
    std::cout << (t1 - t0) << std::endl;
 
    MPI_Finalize();
}
 
1. 執行三個processors: mpiexec -n 3
2. processor#0只睡2秒因此最先醒來列印1~5
  processor#2 睡3秒因此第二醒來列印1~5
  processor#1 睡5秒因此最後醒來列印 1~5
3. 先完成的processor需等待其他較慢的processor
4. 全部到齊,才開始下一回合
5. processor#1只睡1秒因此最先醒來列印6~10
  processor#0 睡3秒因此第二醒來列印6~10
  processor#2 睡4秒因此最後醒來列印6~10

 

 

另一個解釋MPI_Barrier的例子

 

https://youtu.be/q9OfXis50Rg?t=1299

 

 

 

 

 

 

 

arrow
arrow
    全站熱搜

    me1237guy 發表在 痞客邦 留言(0) 人氣()