Python - 协程管理
2021-04-23 03:27
标签:任务 pip port event time() 语法 生成 rom 退出 Python - 协程管理 标签:任务 pip port event time() 语法 生成 rom 退出 原文地址:https://www.cnblogs.com/noise/p/14687167.html 1 """
2 协程:实现多任务的另一种方式;
3 单线程的并发,又称微线程;
4 一种用户态的轻量级线程
5
6 特性:
7 对于协程来说,程序员就是上帝,你想让她执行到哪里,他就执行到哪里--实现任务的任意切换
8 原理:能够保留上一次调用的状态(生成器也有这个功能)
9 意义:线程间切换需耗时(保存状态,下次继续),协程只使用一个线程,切换耗费更少的资源。
10
11 应用场景:如果一个线程里面IO操作特别多,协程(与线程相比)的执行效率更高
12
13 """
14
15
16 def learn():
17
18 yield ‘语法‘
19 yield ‘数学‘
20 yield ‘英语‘
21
22
23 def work():
24
25 yield ‘SDR02150‘
26 yield ‘SDR02151‘
27 yield ‘SDR02152‘
28 yield ‘SDR02153‘
29
30
31 if __name__ == ‘__main__‘:
32
33 t1 = learn()
34 t2 = work()
35 #
36 # print(next(t1))
37 # print(next(t2))
38 # print(next(t1))
39 # print(next(t2))
40 # print(next(t1))
41 # print(next(t2))
42 # print(next(t2))
43 #
44 for i in t1: #生成器本身是迭代器 拥有next(),iter()
45 print(i)
46
47
48
49
50 """
51 greenlet:是一个轻量级的协程
52
53 1> 安装模块 pip install greenlet
54 2> 对象.switch()实现任务的切换
55
56 """
57
58 from greenlet import greenlet
59
60 def eat():
61 print("eating")
62
63
64 def sleepp(): #sleep 可能和其他函数名重复
65 print("sleeping")
66
67
68 g1 = greenlet(eat)
69 g2 = greenlet(sleepp)
70
71 g1.switch() #切换到g1运行
72 g2.switch() #切换到g2运行
73
74
75
76 """
77
78 特点:可实现任务的自动切换(遇到PF10),属于主动式切换;
79 主要模式:gevenlet
80 安装 pip install gevent
81
82
83 1. gevent.spawn(func,1,2,3,x=4,x=5) # 创建一个协程对象
84 2. join() 阻塞
85 3. joinall() 方法的参数是一个协程对象列表,他会等待所有的协程都执行完毕后再退出
86
87 """
88
89 import gevent
90 import time
91 # from gevent import monkey
92 # monkey.patch_all()
93
94 # 打补丁,为了能识别time.sleep()为一个耗时操作,来模拟IO操作
95 # 功能:模块运行时特换的功能
96
97 def eat():
98 print("eating")
99 gevent.sleep(2)
100 # time.sleep(2)
101 print("eating222")
102
103
104 def sleepp(): #sleep 可能和其他函数名重复
105 print("sleeping")
106 gevent.sleep(2)
107 # time.sleep(2)
108 print("sleeping222")
109
110
111 gevent.joinall([
112 gevent.spawn(eat),
113 gevent.spawn(sleepp)
114 ]
115 )
116
117
118 # if __name__ == ‘__main__‘:
119 # g1 = gevent.spawn(eat)
120 # g2 = gevent.spawn(sleepp)
121 #
122 # g1.join()
123 # g2.join()
124 #
125 # print("haha")
126
127
128
129
130 import gevent
131 import time
132
133
134
135 def boy():
136 print("boy :i have some to you")
137 gevent.sleep(2)
138 print("boy :i love you")
139
140
141 def girl():
142 print("girl :what?")
143 gevent.sleep(2)
144 print("girl :please be good at python before love")
145
146
147 def people():
148 print("people:what are they talking about ?")
149 gevent.sleep(2)
150 print("people:waooooooooo")
151
152
153
154 t1 = time.time()
155
156 gevent.joinall([
157 gevent.spawn(boy),
158 gevent.spawn(girl),
159 gevent.spawn(people)
160 ])
161
162 t2 = time.time()
163
164 print("the elapsed time:{}".format(t2-t1))
165
166
167 # boy :i have some to you
168 # girl :what?
169 # people:what are they talking about ?
170 # boy :i love you
171 # girl :please be good at python before love
172 # people:waooooooooo
173 # the elapsed time:2.0172317028045654
上一篇:线程通知
下一篇:Spring注解大全