How do you close an unknown number of shard resources together?
ExitStack registers a variable number of cleanup actions at runtime and unwinds them in reverse registration order.
Python example and interpretation
Register shard A and then B. B is released first. Register as soon as a resource is acquired so a later acquisition failure still unwinds earlier resources.
from contextlib import ExitStack
closed=[]
with ExitStack() as stack:
stack.callback(closed.append,'A')
stack.callback(closed.append,'B')
closedResult ['B', 'A']
中文
批量打开数量不定的分片时怎样统一释放资源?
ExitStack 可在运行时登记多个退出操作,离开作用域时按登记的逆序调用。
Python 算例与适用条件
先登记分片 A 再登记 B,退出时先关闭 B。获取到资源后应立即登记,确保后续获取失败时已取得的资源仍能释放。
from contextlib import ExitStack
closed=[]
with ExitStack() as stack:
stack.callback(closed.append,'A')
stack.callback(closed.append,'B')
closed结果 ['B', 'A']