首页 > 解决方案 > 如何根据 CMake 变量拥有一个串行和并行工作的代码

问题描述

CMake 的摘录显示了我如何定义PARALLEL要传递到代码中的标志:

option(ENABLE_MPI "Enable MPI parallelization" OFF)

SET(PARALLEL 0 CACHE INTEGER "Defines a Parallel Build")

if(ENABLE_MPI)
    find_package(MPI REQUIRED)
    include_directories(${MPI_INCLUDE_PATH})
    set(CMAKE_C_FLAGS "${CMAKE_FLAGS} ${MPI_FLAGS}")
    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${MPI_CXX_FLAGS}")
    set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} ${MPI_EXE_LINKER_FLAGS}")
    add_subdirectory(third-party/parmetis-4.0.3)
    unset(PARALLEL CACHE)
    SET(PARALLEL 1 CACHE INTEGER "Defines a Parallel Build")
    add_definitions( -DPARALLEL=${PARALLEL} )
endif(ENABLE_MPI)

在我的 C 代码中,我有一个这样的选项:

#ifndef PARALLEL
#  define PARALLEL @PARALLEL@
#endif

int main(int argc, char **argv){
    int world_rank =0;
    int world_size=0;

    if (PARALLEL) {
        printf("This is a parallel build!\n");
        // Initialize the MPI environment
        MPI_Init(NULL, NULL);

        // Get the number of processes
        int world_size;
        MPI_Comm_size(MPI_COMM_WORLD, &world_size);

        // Get the rank of the process
        int world_rank;
        MPI_Comm_rank(MPI_COMM_WORLD, &world_rank);

        // Get the name of the processor
        char processor_name[MPI_MAX_PROCESSOR_NAME];
        int name_len;
        MPI_Get_processor_name(processor_name, &name_len);

        // Print off a hello world message
        printf("Hello world from processor %s, rank %d out of %d processors\n",
            processor_name, world_rank, world_size);
         if (world_rank == 0) {
            //read inputfile and initalize
            printf("rank ID %d\n",world_rank);
        }
    }
    else {
        printf("This is NOT a parallel build!\n");
    }

    if (world_rank == 0) {
            //read inputfile and initalize
       printf("rank ID %d: Read Inputfile \n",world_rank);
       if (PARALLEL) {
           printf("rank ID %d: Parition Mesh with %d Partitions\n",world_rank,world_size);
       }else{printf("rank ID %d: Serial Simulation - No Mesh Partitioning \n", world_rank); }
     }

   //ReadInputFile(argv[1]);
   //WriteVTU(argv[1]);
   //FreeArrays();

   if (PARALLEL) {
       // Finalize the MPI environment.
       MPI_Finalize();
   }

   return 0;
}

我从中得到的输出(使用并行构建)是:

This is a parallel build!
Hello world from processor -----, rank 0 out of 2 processors
rank ID 0
rank ID 0: Read Inputfile
rank ID 0: Parition Mesh with 0 Partitions
This is a parallel build!
Hello world from processor ----, rank 1 out of 2 processors
rank ID 0: Read Inputfile
rank ID 0: Parition Mesh with 0 Partitions

有没有办法编写可以串行编译(比如使用 cc)和并行编译(使用 mpicc)的单个程序?

标签: ccmakempi

解决方案


推荐阅读