list_generator


协程

单线程的并发效果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
# #Author:raydied
# a = []
# for i in range(10):
# a.append(i*2)
# print(a)
#
# #或者,使用列表生成器,调用的时候才会生成列表,不占内存
# # 但是不能使用切片选择,只记住列表中的某一个值,只能一个挨着一个取出来,用__next__()取出。
# a_1 = [i*2 for i in range(10)]
# print(a_1)

import random,sys,time

store_bun = ["韭菜", "芹菜", "萝卜", "大肉", "牛肉", "鸡蛋"]

def error():
print("check you input!")
exit()

def digit(arg):
if arg.isdigit():
arg = int(arg)
else:
error()
return arg

def doing():
for i in range(59):
sys.stdout.write("#")
sys.stdout.flush()
time.sleep(0.05)

print("welcom to the bun store".center(60,"-"))
for index,buns in enumerate(store_bun):
print("No.%d ---->the[%s]bun".center(60)%(index,buns))
which_bun = input("which one do you like,input the number:")
which_bun = digit(which_bun)

if which_bun >= 0 and which_bun < len(store_bun):
pass
else:
error()

producer_bun = store_bun[which_bun]

user_sum = input("? how many consumer: ")
user_sum = digit(user_sum)
bun_sum = input("? how many buns to buy: ")
bun_sum = digit(bun_sum)

user = []
for i in range(user_sum):
user_name = input("please input the NO.%d consumer's name:"%(i+1))
user.append(user_name)

# def p_bun():
# global producer_bun
#
# producer_bun = random.sample(bun,1)
# return producer_bun#错误思路

# n = 0
# while n < 10:
# producer_bun = random.sample(bun,1)
# n += 1
# user = "ray"
# user_bun = "pig"
def consumer():
print("%s is ready to eat buns"%user)
while True:
bun = yield
for i in range(user_sum):
print("%s bun is eating by %s"%(producer_bun,user[i]))

def producer():
c = []
for i in range(user_sum):
c.append("消费者")
for i in range(user_sum):
c[i] = consumer()
c[i].__next__()
# c1=consumer()
# c1.__next__()
print(" %s buns is doing" %producer_bun)
for i in range(bun_sum):
print("the No.%d bun".center(60,"=")%(i+1))
doing()
print("\n%s bun was done"%producer_bun)
for i in range(user_sum):
c[i].send(producer_bun)

# c1=consumer()
# c1.__next__()
# c1.__next__()

consumer()
producer()
文章目录
  1. 1. 协程
  2. 2. 单线程的并发效果
|