代码之家  ›  专栏  ›  技术社区  ›  AngusTheMan

用MPI实现C++中的循环并行

  •  0
  • AngusTheMan  · 技术社区  · 7 年前

    我想让我 for C++中的循环并行。迭代是完全独立的。下面是一个类似的程序,它捕获了任务的想法。

    class A{
    
        // create experiment 
        // perform experiment
        // append results to file 
        // reset the experiment 
    
    };
    
    main {
    
        // open a file 
    
        // instance class
        A a;
        int N = 10000;
    
        for ( int i = 0; i <= N; i++ ){
            a.do_something()
        }
    
        // close file
        // return
    }
    

    每次迭代只需将其数据打印到输出文件中,其顺序也不重要。自从 a.do_something() 是很长的,我想把它平行。我已经安装了 MPI 现在我对它的基本用途有些熟悉。

    我的逻辑是分割范围 N 根据可用处理器的数量分区。我正在寻找一些帮助,如何使我的串行版本与MPI并行。我的尝试是:

    class A{
    
        // create experiment 
        // perform experiment
        // append results to file 
        // reset the experiment 
    
    };
    
    main {
    
        // open a file 
    
        // instance class
        A a;
    
    
        // initialise the MPI 
        int ierr = MPI_Init(&argc, &argv);
        int procid, numprocs;
    
        ierr = MPI_Comm_rank(MPI_COMM_WORLD, &procid);
        ierr = MPI_Comm_size(MPI_COMM_WORLD, &numprocs);
    
        // partition = (job size) over (processors). 
        unsigned int partition = N / numprocs;
    
    
        int N = 10000;
    
        for ( int i = 0; i <= N; i++ ){
            a.do_something()
        }
    
    
    
        ierr = MPI_Finalize();
        // close file
        // return
    }
    

    但我真的很难分割for循环,不知道如何继续。

    这将只运行两次串行代码(在我的2核机器上)。我想把for循环拆分为 N/2 并让每个线程处理不同的块。

    我是否需要保留一个核心以将作业广播到其他核心?我可以迭代分区吗?我在网上搜索,运气不好。有什么建议吗?

    1 回复  |  直到 7 年前
        1
  •  0
  •   john    7 年前

    当代码的MPI部分启动时,将其视为在处理器上运行的独立程序。这意味着您编写的循环在两个处理器上独立运行。例如,分割它的方法是

    for ( int i = rank*partition; i <= rank*partition+partition; i++ )
    
    {
        a.do_something()
    }
    

    另外,在使用前声明n:-)