from getopt import gnu_getopt
from re import T
from mpi4py import MPI
import numpy as np
from time import time
import sys
t_start = time()
print(t_start)
comm = MPI.COMM_WORLD
rank = comm.Get_rank()
if rank == 0:
print("主进程开始")
# 输出文件路径
result = "result.txt"
f = open(result, 'w')
# 进程容量
comm_size = comm.Get_size()
# 生成comm_sized长度大小的列表
a = [0 for i in range(comm_size - 1)]
a.insert(0, -1)
a = np.array(a)
# 设置索引
index = 1
while 1:
# 0代表空闲的进程 找出所有为值0的索引生成数组
tempArray = np.where(a == 0)[0]
for i in tempArray:
# 向该进程发送信息
comm.send(index, dest=i, tag=0)
#print("向进程{}发送信息{}".format(i, index))
index += 1
# 值改为1 标识该进程已经使用
a[i] = 1
# 收集子进程发送过来的信息----值为1的表示已经执行
resultArray = np.where(a == 1)[0]
for i in resultArray:
if i == 0:
continue
else:
# 获取子 进程发送回来的消息--字典形式
resultDic = comm.recv(source=i, tag=i)
# 获取id
rankid = resultDic["id"] # 获取进程的编号
#print("收到进程{}的结果:{}".format(rankid, str(resultDic["data"])))
# 告诉该进程已经执行完了,可以调用
a[rankid] = 0
# 写入传回来 计算好的值
f.writelines(str(resultDic["data"]) + '\n')
f.flush()
# 循环1000次
if index > 1000:
# 结束进程
print('gg')
MPI.Finalize()
t_end = time()
t = t_end - t_start
f.writelines(str(t))
print(t)
# 调出循环
break
else:
while 1:
# 获取编号
rankId = comm.Get_rank()
# 获取 index 值
indexNumber = comm.recv(source=0, tag=0)
if indexNumber > 1000:
# 结束进程
MPI.Finalize()
break
else:
# 计算a[i] -乘自己的编号
tempData = indexNumber * 3
# 计算 a[i] * a[i]
res = tempData * tempData
sendData = {"id": rankId, "data": res} # 将进程号和计算结果返回
# 将字典格式的数据发回给主进程
comm.send(sendData, dest=0, tag=comm.Get_rank())