同步与异步
1.同步调用
import time """ 同步调用按顺序进行 """ def longIo(): print("开始处理耗时操作") time.sleep(5) print("结束处理耗时操作") return "sunck is a good man" def reqA(): print("开始处理请求A") res = longIo() print("接收到返回的数据:", res) print("结束处理请求A") def reqB(): print("开始处理请求B") time.sleep(2) print("结束处理请求B") def main(): reqA() reqB() if __name__ == "__main__": main()
2.异步调用之回调函数
import time from threading import Thread """ 异步调用将耗时操作交给别人去进行, 主程序继续往下运行, 然后当执行耗时操作的那个人执行完后在将结果反馈给我们 """ def longIo(callback): def run(callback): print("开始处理耗时操作") time.sleep(5) print("结束处理耗时操作") callback( "sunck is a good man") Thread(target=run, args=(callback,)).start() def finish(res): print('通过回调函数返回出来的结果',res) def reqA(): print("开始处理请求A") longIo(finish) # res = longIo() # print("接收到返回的数据:", res) print("结束处理请求A") def reqB(): print("开始处理请求B") time.sleep(2) print("结束处理请求B") def main(): reqA() reqB() if __name__ == "__main__": main()
3.异步调用之携程简单版
""" 携程之简单版1 """ import time import threading #全局的生成器 gen = None def longIo(): def run(): print("开始处理耗时操作") time.sleep(5) print("结束处理耗时操作,并唤醒请求A") try: gen.send("sunck is a handsome man") except StopIteration as e: pass threading.Thread(target=run).start() def reqA(): print("开始处理请求A") res = yield longIo() print("接收到返回的数据:", res) print("结束处理请求A") def reqB(): print("开始处理请求B") time.sleep(2) print("结束处理请求B") def main(): global gen gen = reqA() next(gen) # 启动gen,yield工作原理, reqA()并没有启动函数,要next()才能启动 reqB() while 1: pass if __name__ == "__main__": main()
4.异步调用之携程提升版
import time import threading #全局的生成器 gen = None def longIo(): def run(): print("开始处理耗时操作") time.sleep(5) print("结束处理耗时操作,并唤醒请求A") try: gen.send("sunck is a handsome man") except StopIteration as e: pass threading.Thread(target=run).start() def reqA_login(func): def inner(*args, **kwargs): global gen gen = func() next(gen) return inner @reqA_login def reqA(): print("开始处理请求A") res = yield longIo() print("接收到返回的数据:", res) print("结束处理请求A") def reqB(): print("开始处理请求B") time.sleep(2) print("结束处理请求B") def main(): reqA() reqB() while 1: pass if __name__ == "__main__": main()
5.异步调用之携程最终版
import time import threading ''' 携程的最终版本去除了全局变量 ''' def longIo(): print('延时操作开始') time.sleep(5) print('延时操作结束') yield 'suck is nb' def reqA_login(func): def inner(*args, **kwargs): # global gen gen = func() # reqA的生成器 g = next(gen) # longIo的生成器 def run(g): res = next(g) print('res',res) threading.Thread(target=run, args=(g,)).start() try: gen.send('dqnwidwqjkdn') except StopIteration as e: pass return inner @reqA_login def reqA(): print("开始处理请求A") res = yield longIo() print("接收到返回的数据:", res) print("结束处理请求A") def reqB(): print("开始处理请求B") time.sleep(2) print("结束处理请求B") def main(): reqA() reqB() if __name__ == "__main__": main()