zoukankan      html  css  js  c++  java
  • PythonStudy——单线程并发的实现

    # 使用yield实现单线程并发多个任务
    # 引子 : 生成器回顾
    # def func1():
    #     print('1')
    #     yield
    #     print('2')
    #     yield
    #     print('3')
    #     yield
    
    
    # res = func1()
    # print(res) # <generator object func1 at 0x109032e60>
    # next(res) # 1
    # next(res) # 2
    # next(res) # 3
    
    # ------------------------------------------------------
    # 正式使用yield实现单线程并发多个任务
    # import time
    #
    # # 加法函数 被并发的那个函数
    # def func1():
    #     a = 1
    #     for i in range(1000):
    #         a += 1
    #         print("a run")
    #         yield
    #
    # def func2():
    #     res = func1()
    #     b = 1
    #     for i in range(1000):
    #         b += 1
    #         print("b run")
    #         next(res)
    #
    # start_time = time.time()
    # func2()
    # end_time = time.time()
    # print("耗时>>>%s"%(end_time-start_time))
    # >>>0.007849931716918945
    # -------------------------------------------------------
    
    # 不采取yield并发程序(默认运行)
    # import time
    #
    #
    # def func1():
    #     a = 1
    #     for i in range(1000):
    #         a += 1
    #         print("a run")
    #
    #
    # def func2():
    #     b = 1
    #     for i in  range(1000):
    #         b += 1
    #         print("b run")
    #
    #
    # start_time = time.time()
    # func1()
    # func2()
    # end_time = time.time()
    # print("耗时>>>%s"%(end_time-start_time))
    # # 耗时>>>0.006770133972167969
    
    # 我们通过数值比较发现
    # 使用yield生成器强行并发单线程中的函数 反而会导致运行速度下降 用时增加
  • 相关阅读:
    单元测试之道读书笔记(七)
    单元测试之道读书笔记(六)
    单元测试之道读书笔记(五)
    单元测试之道读书笔记(三)
    技术网站推荐
    CentOS7部署Haproxy 1.7.2
    Centos7.0配置MySQL主从服务器
    Centos7.0安装mysql5.6
    centos7配置Java环境
    Centos6.5 DNS配置
  • 原文地址:https://www.cnblogs.com/tingguoguoyo/p/10990774.html
Copyright © 2011-2022 走看看