乒乓:互相等对方
(每道题开头都有同一段:六个来源 SOURCES,每项是 (名字, 要等的秒数, 字节数);fetch(name, wait, size) 睡 wait 秒后交回 size——「等」的时候别人能干活。)
a 等 ping 才记「乓」再发 pong;b 先记「乒」发 ping,再等 pong 记「收」。两条线程同时活着才能互相解开:
import threading
ping = threading.Event()
pong = threading.Event()
log = []
def a():
ping.wait()
log.append("乓")
pong.set()
def b():
log.append("乒")
ping.set()
pong.wait()
log.append("收")
ta = threading.Thread(target=a)
tb = threading.Thread(target=b)
ta.start()
tb.start()
ta.join()
tb.join()
print(",".join(log) + "/" + str(ping.is_set() and pong.is_set()))
全部评论