Context Manager线程安全

时间:2015-10-23 12:35:00

标签: python maya contextmanager

使用该代码我希望,它应该打印"输入"马上,然后睡觉,然后打印"退出"。 但它一气呵成。 我怎么能让它运作起来?现在它锁定主应用程序,所以理想情况下我想在一个单独的线程中运行被调用的函数。但随后"进入"和"退出"立即打印,并在睡眠定时器后调用函数。

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()

1 个答案:

答案 0 :(得分:1)

您的代码适合我。

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)

如果你增加睡眠时间,它可能会更明显。

相关问题