上下文管理器线程安全
Context Manager thread safe
我希望使用该代码,它应该立即打印 "enter",然后休眠,然后打印 "exit"。
但它一次性完成所有工作。
我将如何让它工作?现在它锁定了主应用程序,所以理想情况下我想 运行 在单独的线程中调用函数。但是 "enter" 和 "exit" 会立即打印出来,并且在睡眠定时器之后会调用函数。
import time
def test_run():
time.sleep(1)
class Update(object):
def __init__(self):
pass
def __enter__(self):
print 'enter'
def __exit__(self, *_):
print 'exit'
with Update():
test_run()
你的代码适合我。
import time
import threading
def test_run():
time.sleep(5)
def run_update():
with Update():
test_run()
class Update(object):
def __init__(self):
pass
def __enter__(self):
print('enter')
def __exit__(self, *_):
print('exit')
if __name__ == "__main__":
th = threading.Thread(target=run_update)
th.start()
for i in range(100):
print(i)
如果您增加睡眠时间,它可能会更明显。
我希望使用该代码,它应该立即打印 "enter",然后休眠,然后打印 "exit"。 但它一次性完成所有工作。 我将如何让它工作?现在它锁定了主应用程序,所以理想情况下我想 运行 在单独的线程中调用函数。但是 "enter" 和 "exit" 会立即打印出来,并且在睡眠定时器之后会调用函数。
import time
def test_run():
time.sleep(1)
class Update(object):
def __init__(self):
pass
def __enter__(self):
print 'enter'
def __exit__(self, *_):
print 'exit'
with Update():
test_run()
你的代码适合我。
import time
import threading
def test_run():
time.sleep(5)
def run_update():
with Update():
test_run()
class Update(object):
def __init__(self):
pass
def __enter__(self):
print('enter')
def __exit__(self, *_):
print('exit')
if __name__ == "__main__":
th = threading.Thread(target=run_update)
th.start()
for i in range(100):
print(i)
如果您增加睡眠时间,它可能会更明显。