栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

yield能干啥———让函数变成生成器

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

yield能干啥———让函数变成生成器

生成器可以实现代码协成运行

占用资源和时长从大到小:

进程 > 线程 > 协成

两个函数启动时间不同,用 线程和进程没有区别,用协成会等待时间长的运行后在重复,必须遵守一个一个运行。

import time
import threading
import multiprocessing
'''
def task_1():
    while True:
        print("--1--")
        time.sleep(0.1)
        yield  # 可以不用传任何参数

def task_2():
    while True:
        print("--2--")
        time.sleep(1)
        yield # return无法做到

def main():
    t1 = task_1()
    t2 = task_2()
    while True:
        next(t1)
        next(t2)
'''
'''
多线程启动方法:

def task_1():
    while True:
        print("--1--")
        time.sleep(0.1)


def task_2():
    while True:
        print("--2--")
        time.sleep(0.5)


def main():
    t1 = threading.Thread(target=task_1)
    t2 = threading.Thread(target=task_2)

    t1.start()
    t2.start()
    
'''
'''
多进程运行

def task_1():
    while True:
        print("--1--")
        time.sleep(0.1)


def task_2():
    while True:
        print("--2--")
        time.sleep(0.5)


def main():
    t1 = multiprocessing.Process(target=task_1)
    t2 = multiprocessing.Process(target=task_2)

    t1.start()
    t2.start()
    
'''



if __name__ == '__main__':
    main()

 

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/688918.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号