我想要一个上下文管理器,在其中可以将要执行的一些代码放在单独的线程中。
到目前为止,我还找不到找到想要的方法,最好的选择是在单独的线程中编写闭包并执行闭包。
我想要这样的东西
# code runs on main thread
print("this is main thread")
with amazingcontextmanager:
# code to run in separate thread
print("this is not main thread")
编辑:让我尝试再次提出问题
@contextlib.contextmanager
def amazingcontextmanager():
try:
yield
finally:
print("thread done")
我希望yield
在新线程中执行。基本上,我放在contextmanager下的任何内容都应在单独的线程中执行。