我正在编写一个程序,它应该在三个不同的进程中为字符串添加字符。如果结果字符串与给定字符串匹配,则具有匹配的进程应该向进程0发送“endflag”。在进程0接收到“endflag”之后,他应该向所有其他进程(1-3)发送广播并退出。其他进程接收广播,也应退出/停止工作。
[...]
string_given = "abc"
magic_bytes = "0xDEA7C0DE"
chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890 !?@/\%&.-_:,;*+<>|(){}'
end_all = None
if rank == 0:
while(True):
recv_data = comm.recv(source=MPI.ANY_SOURCE)
print("0.recv: %s" % (recv_data))
if recv_data == magic_bytes:
end_all = magic_bytes
send_data = bcast(end_all, root=0)
sys.exit()
if rank == 1:
min, max = 1, 2
while(True):
for n in xrange(min, max):
for c in itertools.product(chars, repeat=n):
string = ''.join(c)
print("1.string: %s" % (string))
if string == string_given:
print("1.found: %s = %s" % (string, string_given))
end_all = magic_bytes
comm.send(end_all, dest=0)
recv_data = comm.bcast(end_all, root=0)
if recv_data == magic_bytes:
sys.exit()
if rank == 2:
min, max = 3, 4
while(True):
for n in xrange(min, max):
for c in itertools.product(chars, repeat=n):
string = ''.join(c)
print("2.string: %s" % (string))
if string == string_given:
print("2.found: %s = %s" % (string, string_given))
end_all = magic_bytes
comm.isend(end_all, dest=0)
recv_data = comm.bcast(end_all, root=0)
if recv_data == magic_bytes:
sys.exit()
[...]
上面的代码产生以下输出:
3.string: aaaaa
1.string: a
2.string: aaa
然后我觉得它陷入僵局。 如何防止我的代码死锁?