我有一个主线程,需要定期将缓冲区刷新到磁盘,因此每次我创建一个新线程来运行 json.dump(buffer) 时。但在此之后我需要立即清除缓冲区,那么 Python 中是否有“移动语义”让我无需对其进行深层复制即可执行此操作?
也许使用包装类来帮助移动。
class ExpensiveObj: pass
class ExpensiveObjHolder:
def __init__(self, obj: ExpensiveObj):
self._obj = obj
def move(self) -> ExpensiveObj:
obj, self._obj = self._obj, None
if not obj:
raise UseAfterMoveError
return obj
def consume_obj(obj: ExpensiveObj):
info = ParseObj(obj)
del obj
some_time_consuming_task(info)
holder = ExpensiveObjHolder(ExpensiveObj())
consume_obj(holder.move()) # passing ownership, ref of obj in holder released.