How do I stop Julia optimising out a variable? (or how to use `MPI.Ibarrier()`?)

You can use GC.@preserve dummy_req to make sure that dummy_req is not finalised within a block of code.

Your particular case is a bit tricky because you want all the 100 requests to be preserved. One solution would be to use an MPI.MultiRequest to store all of them, which could look like:

using MPI

MPI.Init()

comm = MPI.COMM_WORLD
comm_rank = MPI.Comm_rank(comm)

dummy_reqs = MPI.MultiRequest(100)

GC.@preserve dummy_reqs begin
    for i in 1:100
        if comm_rank == 0
            # ... do some work ...
            MPI.Ibarrier(comm, dummy_reqs[i])
        else
            req = MPI.Ibarrier(comm)
            MPI.Wait(req)
            # ... do some other work ...
        end
    end
    MPI.Barrier(comm)  # make sure dummy_reqs hasn't been finalised up to this point
end
2 Likes