tornado同步与异步

同步:按部就班的依次执行代码。


异步:对于耗时的操作,会交给另一个线程处理,原代码继续向下执行,当另一个线程结束后将结果反馈到当前线程。


实现异步的方式:
        回调函数实现异步
        
def longIO(callback):

    def run(cb):
        print("开始耗时操作")
        sleep(5)
        print("结束耗时操作")
        cb("dfsssssssssdfdfdfdfdfdfdfd")
    threading.Thread(target=run,args=(callback,)).start()

def finish(data):
    print("开始处理回调函数")
    print("接收到longIO的响应数据:", data)
    print("结束处理回调函数")

def reqA():
    print("开始处理reqA")
    longIO(finish)
    print("结束处理reqA")

def reqB():
    print("开始处理reqB")
    print("结束处理reqB")

def main():
    reqA()
    reqB()
    while 1:
        sleep(0.1)
        pass

main()

        协程实现异步

from time import sleep
import threading

gen = None
def longIO():

    def run():
        print("开始耗时操作")
        sleep(5)
        try:
            global gen
            gen.send("ddddddddddd")
        except StopIteration:
            pass
    threading.Thread(target=run).start()

def genCoroutine(func):
    def wrapper(*args,**kwargs):
        global gen
        gen = func(*args,**kwargs)
        next(gen)
    return wrapper

@genCoroutine
def reqA():
    print("开始处理reqA")
    res = yield longIO()
    print("接收到的longIO的响应数据:",res)
    print("结束处理reqA")

def reqB():
    print("开始处理reqB")
    print("结束处理reqB")

def main():
    reqA()
    reqB()
    while 1:
        sleep(0.1)
        pass


if __name__ == "__main__":
    main()
协程实现异步(难理解):tornado实现异步和高并发的原理
from time import sleep
import threading

def longIO():
    print("开始耗时操作")
    sleep(5)
    print("结束耗时操作")
    yield "ggggggggggggggggggggggggg"

def genCoroutine(func):
    def wrapper(*args,**kwargs):

        gen1 = func()
        gen2 = next(gen1)

        def run(g):
            res = next(g)
            try:
                gen1.send(res)
            except StopIteration:
                pass
        threading.Thread(target=run,args=(gen2,)).start()
        # global gen
        # gen = func(*args,**kwargs)
        # next(gen)
    return wrapper

@genCoroutine
def reqA():
    print("开始处理reqA")
    res = yield longIO()
    print("接收到的longIO的响应数据:",res)
    print("结束处理reqA")

def reqB():
    print("开始处理reqB")
    print("结束处理reqB")

def main():
    reqA()
    reqB()
    while 1:
        sleep(0.1)
        pass


if __name__ == "__main__":
    main()

猜你喜欢

转载自blog.csdn.net/huolan__34/article/details/80809089
今日推荐