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/coroutine1.py
Views: 729
1
"""
2
使用协程 - 模拟快递中心派发快递
3
4
Version: 0.1
5
Author: 骆昊
6
Date: 2018-03-21
7
"""
8
9
from time import sleep
10
from random import random
11
12
13
def build_deliver_man(man_id):
14
total = 0
15
while True:
16
total += 1
17
print('%d号快递员准备接今天的第%d单.' % (man_id, total))
18
pkg = yield
19
print('%d号快递员收到编号为%s的包裹.' % (man_id, pkg))
20
sleep(random() * 3)
21
22
23
def package_center(deliver_man, max_per_day):
24
num = 1
25
deliver_man.send(None)
26
# next(deliver_man)
27
while num <= max_per_day:
28
package_id = 'PKG-%d' % num
29
deliver_man.send(package_id)
30
num += 1
31
sleep(0.1)
32
deliver_man.close()
33
print('今天的包裹派送完毕!')
34
35
36
dm = build_deliver_man(1)
37
package_center(dm, 10)
38
39
# 两个函数虽然没有调用关系但是创建快递员的函数作为一个协程协助了快递中心函数完成任务
40
# 想一想如果有多个快递员的时候应该如何处理
41
42