方法1蔑水,使用線程,復制代碼執(zhí)行就行虚茶,將? async_fun當作裝飾器放在 需要 異步非阻塞的函數(shù)上就可以了
import time
from threading import Thread
def async_fun(f):
? ? def inner_fun(*args, **kwargs):
? ? ? ? t = Thread(target=f, args=args, kwargs=kwargs)
? ? ? ? t.start()
? ? return inner_fun
@async_fun
def test_a():
? ? time.sleep(10)
? ? print("test a run")
def test_b():
????test_a()
? ? print("test b run")
test_b()
方案二讨阻, 線程池,??
from concurrent.futuresimport ThreadPoolExecutor
import time
def test(times):
????time.sleep(times)
????print("over_test")
t = ThreadPoolExecutor(max_workers=2)
# 通過submit函數(shù)提交執(zhí)行的函數(shù)到線程池中,submit函數(shù)立即返回庄蹋,不阻塞
t.submit(test, 2)
print('over')
最后運行結果是瞬内,先over,? ?然后over_test