方法1,使用线程,复制代码执行就行,将 async_fun当作装饰器放在 需要 异步非阻塞的函数上就可以了
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函数提交执行的函数到线程池中,submit函数立即返回,不阻塞
t.submit(test, 2)
print('over')
最后运行结果是,先over, 然后over_test