在上一篇我们介绍了 mpi4py 中非重复非阻塞标准通信模式,下面我们将介绍非重复非阻塞缓冲通信。
非重复非阻塞的缓冲通信模式是与阻塞的缓冲通信模式相对应的,其通信方法(MPI.Comm 类的方法)接口有一个前缀修饰 I/i,如下:
ibsend(self, obj, int dest, int tag=0)
irecv(self, buf=None, int source=ANY_SOURCE, int tag=ANY_TAG)
Ibsend(self, buf, int dest, int tag=0)
Irecv(self, buf, int source=ANY_SOURCE, int tag=ANY_TAG)
这些方法调用中的参数是与阻塞标准通信模式的方法调用参数一样的。
需要注意的是,上面虽然给出的是非阻塞的发送和非阻塞的接收方法,但非阻塞发送可与阻塞接收相匹配,反之,阻塞发送也可与非阻塞接收相匹配。
下面给出非重复非阻塞缓冲通信的使用例程:
# ibsend_irecv.py
from mpi4py import MPI
comm = MPI.COMM_WORLD
rank = comm.Get_rank()
# MPI.BSEND_OVERHEAD gives the extra overhead in buffered mode
BUFSISE = 2000 + MPI.BSEND_OVERHEAD
buf = bytearray(BUFSISE)
# Attach a user-provided buffer for sending in buffered mode
MPI.Attach_buffer(buf)
send_obj = {'a': [1, 2.4, 'abc', -2.3+3.4J],
'b': {2, 3, 4}}
if rank == 0:
send_req = comm.ibsend(send_obj, dest=1, tag=11)
send_req.wait()
print 'process %d sends %s' % (rank, send_obj)
elif rank == 1:
recv_req = comm.irecv(source=0, tag=11)
recv_obj = recv_req.wait()
print 'process %d receives %s' % (rank, recv_obj)
# Remove an existing attached buffer
MPI.Detach_buffer()
运行结果如下:
$ mpiexec -n 2 python ibsend-irecv.py
process 0 sends {'a': [1, 2.4, 'abc', (-2.3+3.4j)], 'b': set([2, 3, 4])}
process 1 receives {'a': [1, 2.4, 'abc', (-2.3+3.4j)], 'b': set([2, 3, 4])}
# Ibsend_Irecv.py
import numpy as np
from mpi4py import MPI
comm = MPI.COMM_WORLD
rank = comm.Get_rank()
# MPI.BSEND_OVERHEAD gives the extra overhead in buffered mode
BUFSISE = 2000 + MPI.BSEND_OVERHEAD
buf = bytearray(BUFSISE)
# Attach a user-provided buffer for sending in buffered mode
MPI.Attach_buffer(buf)
count = 10
send_buf = np.arange(count, dtype='i')
recv_buf = np.empty(count, dtype='i')
if rank == 0:
send_req = comm.Ibsend(send_buf, dest=1, tag=11)
send_req.Wait()
print 'process %d sends %s' % (rank, send_buf)
elif rank == 1:
recv_req = comm.Irecv(recv_buf, source=0, tag=11)
recv_req.Wait()
print 'process %d receives %s' % (rank, recv_buf)
# Remove an existing attached buffer
MPI.Detach_buffer()
运行结果如下:
$ mpiexec -n 2 python Ibsend_Irecv.py
process 0 sends [0 1 2 3 4 5 6 7 8 9]
process 1 receives [0 1 2 3 4 5 6 7 8 9]
上面我们介绍了 mpi4py 中非重复非阻塞缓冲通信模式,在下一篇中我们将介绍非重复非阻塞就绪通信。