python异步_Python通过Thread实现异步
生活随笔
收集整理的這篇文章主要介紹了
python异步_Python通过Thread实现异步
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
當long函數(shù)耗時較長時,需要程序先向下執(zhí)行,這就需要異步,改寫代碼如下:
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()
回調(diào)函數(shù)作為參數(shù)傳遞給耗時較長的代碼所在的函數(shù),在新線程執(zhí)行耗時較長的代碼,執(zhí)行完之后把數(shù)據(jù)傳遞給回調(diào)函數(shù),再進行處理。
總結(jié)
以上是生活随笔為你收集整理的python异步_Python通过Thread实现异步的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: UML 模型
- 下一篇: python爬取知乎live_Pytho