Search code examples
pythonmayacontextmanager

Context Manager thread safe


With that code I am hoping, that it should print "enter" right away, then sleep, then print "exit". But it does it all in one go. How would I get it to work? And right now its locking the main application, so ideally I want to run the called function in a separate thread. But then "enter" and "exit" are printed immediately, and after the sleep timer the function call.

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

Solution

  • Your code works for me.

    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)
    

    If you increase the sleep time it might be more noticeable.