python异步实现方式_Python通过yield实现异步
改寫程序first函數(shù)等待long函數(shù)返回值的方式為yield,代碼如下:
import _thread
import time
gen = None
def long():
print ('long execute')
def fun():
time.sleep(5)
result = 'long end'
gen.send(result)
_thread.start_new_thread(fun,())
def first():
print ('first execute')
ret = yield long()
print (ret)
print ('fisrt end')
def second():
print ('second execute')
print ('second end')
def main():
global gen
gen = first()
gen.__next__()
second()
if __name__=='__main__':
main()
解釋一下:定義了全局變量gen,將first()函數(shù)賦值給gen,gen實(shí)際是一個(gè)生成器,因?yàn)閒irst函數(shù)中有yield,當(dāng)運(yùn)行g(shù)en.__next()__時(shí),程序運(yùn)行到y(tǒng)ield代碼,暫停,相當(dāng)于first()函數(shù)已經(jīng)返回,long函數(shù)開始執(zhí)行,主線程繼續(xù)向下執(zhí)行,long函數(shù)中新起了一個(gè)線程,該線程執(zhí)行fun函數(shù),fun函數(shù)執(zhí)行完成通過gen.send(result)方式,將result的值賦給first函數(shù)中的ret,同時(shí)first函數(shù)尋找下一個(gè)yield關(guān)鍵字,由于沒有yield關(guān)鍵字程序會(huì)報(bào)錯(cuò)。
總結(jié)
以上是生活随笔為你收集整理的python异步实现方式_Python通过yield实现异步的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 金生相伴养老保险单借款指什么
- 下一篇: jupyter notebook怎么写p