使用GDB在本地调试MPI程序

1.为了使得gdb能够正常调试进程,可以使用sleep()+while循环的形式,然后用GDB更改while中的变量来切入进程调试。

int flag=1;
    while(flag)
    {
        sleep(1);
    }

2.启动进程,这里使用两个进程作为测试:

mpicc -g -o mpi_test mpi_test.c
mpirun -np 2 ./mpi_test

3.使用ps指令(process statue)寻找进程,然后把结果通过通道传递grep来寻找启动的进程。

ps aux | grep mpi_test
(gdb) shell ps aux|grep mpi_test
zyh        50973  0.0  0.0   7120  3540 pts/5    S+   14:10   0:00 mpirun -np 2 ./mpi_test
zyh        50975  0.0  0.0 119164 13244 ?        Ssl  14:10   0:00 ./mpi_test
zyh        50976  0.0  0.0 119164 13312 ?        Ssl  14:10   0:00 ./mpi_test
zyh        51325  0.0  0.0   4784  3136 pts/7    S+   14:10   0:00 bash -c ps aux|grep mpi_test
zyh        51327  0.0  0.0   4028  2104 pts/7    S+   14:10   0:00 grep mpi_test

4.使用attach,使得gdb挂载到相应的进程上。

(gdb) attach 50975
Attaching to process 50975

5.修改while循环中的flag,使得程序能够向下继续:

(gdb) p flag =0
$1 = 0

6.下面就可以愉快的调试了,比如我们可以打在某个地方打上断点,如果使用continue就会跳到这个断点,或者使用n进行单步调试,step选择步入。但要注意的是,由于很多MPI函数都是同步的,所以会出现一个barrier等待所有进程到达才能放行的情况,调试的时候要注意这种情况!

测试用代码:

#include <stdio.h>
#include <stdlib.h>
#include <mpi.h>
#include <time.h>
#include <unistd.h>


int main(int argc, char **argv) {


  
    int rank, size;
    long long int num_points = 1000000; // 每个进程生成的随机点数
    long long int count = 0; // 落在单位圆内的点数
    double x, y;
    // 初始化 MPI
    MPI_Init(&argc, &argv);  // 初始化MPI环境
    int flag=1;
    while(flag)
    {
        sleep(1);
    }
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);
    MPI_Comm_size(MPI_COMM_WORLD, &size);

    // 每个进程生成随机数的种子
    srand(time(NULL) + rank);

    // 生成随机点并计算落在单位圆内的点数
    for (long long int i = 0; i < num_points; i++) {
        x = (double)rand() / RAND_MAX; // [0, 1)
        y = (double)rand() / RAND_MAX; // [0, 1)
        if (x * x + y * y <= 1) {
            count++;
        }
    }

    // 收集各进程的计数
    long long int total_count;
    MPI_Reduce(&count, &total_count, 1, MPI_LONG_LONG, MPI_SUM, 0, MPI_COMM_WORLD);

    // 计算 π
    if (rank == 0) {
        double pi = 4.0 * total_count / (num_points * size);
        printf("Estimated value of π: %lf\n", pi);
    }

    // 结束 MPI
    MPI_Finalize();
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值