zoukankan      html  css  js  c++  java
  • 学习笔记 线程异步请求过程

    记录学习线程异步请求的过程

    版本1

    不使用线程时,正常情况下执行过程。

    # -*- coding:utf-8  -*-
    # 日期:2018/5/27 14:50
    # Author:小鼠标
    import time
    def a():
        print('a函数开始执行')
        res =  long_io()
        print('========', res)
        print('a函数执行结束')
    def b():
        print('b函数开始执行')
        time.sleep(2)
        print("b函数执行结束")
    def long_io():
        print("执行长时间的io操作")
        time.sleep(5)
        print("io操作完成")
        return 'io结果返回'
    def main():
        a()
        b()
    
    if __name__ == '__main__':
        main()

    版本二

    开启新的线程去执行费时的操作,提高程序执行的速度,加入回调函数

    # -*- coding:utf-8  -*-
    # 日期:2018/5/27 14:50
    # Author:小鼠标
    import time
    import _thread
    
    def a():
        print('a函数开始执行')
        long_io(on_finish)
        print('a函数执行结束')
    def on_finish(res):
        print(res)
    def b():
        print('b函数开始执行')
        time.sleep(2)
        print("b函数执行结束")
    #修改长时间的io函数,开启新的线程执行该操作,
    #用回调函数执行返回结果
    def long_io(callback):
        def func(callback):
            print("执行长时间的io操作")
            time.sleep(5)
            print("io操作完成")
            callback('io结果返回===(回调函数执行)')
        _thread.start_new_thread(func,(callback,))
    def main():
        a()
        b()
        #为了子程序能执行完成
        while 1:
            pass
    
    if __name__ == '__main__':
        main()

    版本三

    用yield和全局变量实现函数的回调

    # -*- coding:utf-8  -*-
    # 日期:2018/5/27 14:25
    # Author:小鼠标
    
    
    import time
    import _thread
    def c(f):
        def index():
            m = f()
            r = next(m)
            def func(r):
                print("开启新的线程处理问题")
                ioRes = next(r)
                try:
                    r.send(ioRes)
                except StopIteration:
                    pass
            _thread.start_new_thread(func,(r,))
        return index
    
    
    @c
    def a():
        print('a函数开始执行')
        res = yield long_io()
        print('========', res)
        print('a函数执行结束')
    
    def b():
        print('b函数开始执行')
        time.sleep(2)
        print("b函数执行结束")
    def long_io():
        print("执行长时间的io操作")
        time.sleep(5)
        print("io操作完成")
        yield 'io结果返回'
    def main():
        a()
        b()
        while 1:
            pass
    
    
    if __name__ == '__main__':
        main()
  • 相关阅读:
    setTimeout和setInterval的区别(面试题)
    什么是跨域?列出几种JS跨域解决方法?(前端面试题)
    建网站的流程
    CSS Sprite(雪碧图)简单使用
    前端不得不说的性能优化
    面试题
    前端如何做好SEO优化
    JavaScript string字符串对象常见方法
    微信号复制跟跳转——clipboard.js
    微信号复制跟跳转——execCommand()
  • 原文地址:https://www.cnblogs.com/7749ha/p/9096165.html
Copyright © 2011-2022 走看看