纯python代码的异步回调
# _*_ encoding:utf-8 _*_
import time
import threading
callback_value = None
onFlag = Truedef add(a, b, num):print(f"I am the function: %s, please wait for %d" % (add.__name__, num))time.sleep(num)c = a + bprint("a + b 1 = ", (a + b))return cdef sub(a, b, num):print(f"I am the function: %s, please wait for %d" % (sub.__name__, num))time.sleep(num)c = a - bprint("a - b 2 = ", (a + b))return c# 同步调用:不另开线程,堵塞,可以立即拿到回调结果
def test_1(ft, a, b, num):print('同步调用:不另开线程,可以立即拿到回调结果')print("After 3 seconds, print the function value")ft(a, b, num)# 异步调用:另开线程,不堵塞,不能立即拿到结果
def test_2(ft, a, b, num):print('异步调用:另开线程,不堵塞,不能立即拿到结果')print("After 3 seconds, print the function value")thread = threading.Thread(target=ft, args=[a, b, num], daemon=False)thread.start()# 定义自己的回调函数
def callback(value):global callback_valuecallback_value = valueprint("我是回调函数")return callback_value# 定义回调函数并在函数中添加自己的回调函数
def add_2(a, b, num, c_b):print(f"I am the function: %s, please wait for %d" % (add_2.__name__, num))time.sleep(num)print("a + b 3 = ", (a + b))res = a + btime.sleep(5)global onFlagonFlag = Falsec_b(res)# 异步回调:另开线程,并定义自己的回调函数来接收别人调用自己以便通知自己回调函数的值,不堵塞,回调结果别通知
def test_3(ft, a, b, num, c_b):print('异步回调:另开线程,并定义自己的回调函数来接收别人调用自己以便通知自己回调函数的值,不堵塞,回调结果别通知')print("After 3 seconds, print the function value")thread = threading.Thread(target=ft, args=[a, b, num, c_b], daemon=False)thread.start()while onFlag:time.sleep(1)if callback_value:print("callback value: ", callback_value)if callback_value == 3:print("get the callback value")if __name__ == '__main__':# test_1(add, 1, 2, 4)# test_2(sub, 1, 2, 4)test_3(add_2, 1, 2, 4, callback)print("test function is completed")
输出:
异步回调:另开线程,并定义自己的回调函数来接收别人调用自己以便通知自己回调函数的值,不堵塞,回调结果别通知
After 3 seconds, print the function value
I am the function: add_2, please wait for 4
a + b 3 = 3
我是回调函数
callback value: 3
get the callback value
test function is completedProcess finished with exit code 0