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()

四、




posted @ 2019-06-24 10:17  zhouhaiwu  阅读(396)  评论(0编辑  收藏  举报