當long函數耗時較長時,需要程序先向下執行,這就需要異步,改寫代碼如下:
import _thread
import time
def long(cb):
print ('long execute')
def fun(callback):
time.sleep(5)
result = 'long end'
callback(result)
_thread.start_new_thread(fun,(cb,))
def on_long_finsh(result):
print (result)
def first():
print ('first execute')
long(on_long_finsh)
print ('fisrt end')
def second():
print ('second execute')
time.sleep(2)
print ('second end')
def main():
first()
second()
if __name__=='__main__':
main()
回調函數作為參數傳遞給耗時較長的代碼所在的函數,在新線程執行耗時較長的代碼,執行完之后把數據傳遞給回調函數,再進行處理。