CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
jackfrued

CoCalc provides the best real-time collaborative environment for Jupyter Notebooks, LaTeX documents, and SageMath, scalable from individual users to large groups and classes!

GitHub Repository: jackfrued/Python-100-Days
Path: blob/master/Day01-15/code/Day13/asyncio1.py
Views: 729
1
"""
2
异步I/O操作 - asyncio模块
3
4
Version: 0.1
5
Author: 骆昊
6
Date: 2018-03-21
7
"""
8
9
import asyncio
10
import threading
11
# import time
12
13
14
@asyncio.coroutine
15
def hello():
16
print('%s: hello, world!' % threading.current_thread())
17
# 休眠不会阻塞主线程因为使用了异步I/O操作
18
# 注意有yield from才会等待休眠操作执行完成
19
yield from asyncio.sleep(2)
20
# asyncio.sleep(1)
21
# time.sleep(1)
22
print('%s: goodbye, world!' % threading.current_thread())
23
24
25
loop = asyncio.get_event_loop()
26
tasks = [hello(), hello()]
27
# 等待两个异步I/O操作执行结束
28
loop.run_until_complete(asyncio.wait(tasks))
29
print('game over!')
30
loop.close()
31
32