2015-10-23 54 views
0

有了這個代碼,我希望它應該立即打印「輸入」,然後睡覺,然後打印「退出」。 但它一氣呵成。 我將如何獲得它的工作?現在它鎖定主應用程序,所以理想情況下我想在單獨的線程中運行被調用的函數。但是然後立即打印「進入」和「退出」,並在睡眠計時器之後進行函數調用。上下文管理器線程安全

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

我沒有看到任何代碼問題。我測試了它並增加了計時器,添加了一些打印語句,並且表現得像預期的那樣。 – idjaw

回答

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) 

如果增加睡眠時間可能會更明顯。

+0

當Update()上下文在函數中時,它似乎只是工作。 謝謝!現在我有更先進的東西,QT不是線程安全的,或者有時候.. – arvidurs