Reputation: 52
I'd like to use the faster Send (not the slower send) method to transmit some characters from one process to another, but haven't been able to get a working solution with mpi4py (restricted to using this language, Python3)
Here's my toy code - if anyone can point out what I'm doing wrong (and how to fix it), I'd be very grateful.
from mpi4py import MPI
import numpy
from array import array
comm = MPI.COMM_WORLD
if comm.rank == 0:
comm.Send([b'hello',MPI.CHAR],dest=1)
elif comm.rank == 1:
buf = array('b')*255
r = comm.Recv([buf,MPI.CHAR],source=0)
print(r)
For reference, I also tried the code here (didnt work): https://groups.google.com/g/mpi4py/c/LDHbzApI55c/m/gENCO-_HAwUJ
Thanks!
Upvotes: 1
Views: 777
Reputation: 194
The problem is that your buffer buf
in this case is not big enough to fit your message when it tries to receive it as it is of length 0.
The solution here is to use a bytearray
as you can initialise it on a fixed size, so your example will be:
from mpi4py import MPI
comm = MPI.COMM_WORLD
if comm.rank == 0:
comm.Send([b'hello',MPI.CHAR],dest=1)
elif comm.rank == 1:
buf = bytearray(256)
comm.Recv([buf,MPI.CHAR],source=0)
# Decode the string to remove the empty characters from bytearray
print(buf.decode('utf-8'))
Also notice that the Recv does not return a value so r will be empty. The result will be saved directly to buf
Upvotes: 2