• Python---协程---重写多线程


    一、

    # 用协程的方式,修改播放电影和音乐的练习题

    # 用协程的方式完成播放

    movie_list = ["斗破.mp4", "复仇者联盟.avi", "钢铁雨.rmvb", "xxx.mp4"]
    music_list = ["周杰伦.mp3", "五月天.mp3"]
    movie_format = ['mp4', 'avi']
    music_format = ['mp3']

    import time
    import asyncio

    #async await
    @asyncio.coroutine
    def play(playlist):
    for i in playlist:
    if i.split(".")[1] in movie_format:
    print("now playing movie named {}".format(i))
    yield time.sleep(1)
    elif i.split(".")[1] in music_format:
    print("now playing music named {}".format(i))
    yield time.sleep(2)
    else:
    print("NO SUPPORTED")

    loop = asyncio.get_event_loop()
    task = [play(movie_list), play(music_list)]
    loop.run_until_complete(asyncio.wait(task))
    loop.close()

    二、

    # 用协程的方式完成播放

    movie_list = ["斗破.mp4", "复仇者联盟.avi", "钢铁雨.rmvb", "xxx.mp4"]
    music_list = ["周杰伦.mp3", "五月天.mp3"]
    movie_format = ['mp4', 'avi']
    music_format = ['mp3']

    import time
    import asyncio

    #async await
    #@asyncio.coroutine
    async def play(playlist):
    for i in playlist:
    if i.split(".")[1] in movie_format:
    print("now playing movie named {}".format(i))
    await asyncio.sleep(1)
    elif i.split(".")[1] in music_format:
    print("now playing music named {}".format(i))
    await asyncio.sleep(2)
    else:
    print("NO SUPPORTED")

    loop = asyncio.get_event_loop()
    task = [play(movie_list), play(music_list)]
    loop.run_until_complete(asyncio.wait(task))
    loop.close()
    三、#### 使用协程的概念,达到以下目的,输入a、b、c、d四个整数,打印出(a+b)*(c+d)的值,假设a+b和c+d是一个耗时一秒的IO操作

    #  encoding:utf-8

    # 使用协程的概念,达到以下目的,输入a、b、c、d四个整数,打印出(a+b)*(c+d)的值,假设a+b和c+d是一个耗时一秒的IO操作

    import asyncio
    import threading
    async def sum(a, b):
    print("now begin cacl, current thread is {}".format(threading.currentThread()))
    r = int(a) + int(b)
    await asyncio.sleep(1)
    print("现在计算完了,current thread is {}".format(threading.currentThread()))
    return r

    loop = asyncio.get_event_loop()
    task = asyncio.gather(sum(1,2), sum(3,4))
    loop.run_until_complete(task)
    r1,r2 = task.result()
    print(int(r1)*int(r2))
    loop.close()

    四、




  • 相关阅读:
    MYSQL数据库基础
    MSYQL操数据DML
    MYSQL外键约束
    MYSQL多表查询
    MYSQL结果排序、分页查询、聚合函数
    未能加载文件或程序集“System.Data.SQLite”或它的某一个依赖项”的解决方法
    由于扩展配置问题而无法提供您请求的页面。
    JS中的prototype(转载)
    mvc表单如何绑定bool类型的属性或变量
    使用c#正则验证关键字并找出匹配项
  • 原文地址:https://www.cnblogs.com/niaocaizhou/p/11075659.html
Copyright © 2020-2023  润新知