共学Python:gevent

gevent

greenlet已经实现了协程,但是是还之人造切换,是匪是认为最好难为了,不要捉急,python还有一个比较greenlet更有力的以能自行切换任务之模块gevent

彼规律是当一个greenlet遇到IO(指的凡input output
输入输出,比如网络、文件操作等)操作时,比如看网络,就自动切换到外的greenlet,等交IO操作就,再当适用的时节切换回来继续执行。

出于IO操作十分耗时,经常要程序处于等候状态,有了gevent为咱自行切换协程,就确保总起greenlet在运行,而不是等IO

安装

pip3 install gevent

  1. gevent的使用

import gevent

def f(n):
for i in range(n):
print(gevent.getcurrent(), i)

g1 = gevent.spawn(f, 5)
g2 = gevent.spawn(f, 5)
g3 = gevent.spawn(f, 5)
g1.join()
g2.join()
g3.join()
运转结果

<Greenlet at 0x10e49f550: f(5)> 0
<Greenlet at 0x10e49f550: f(5)> 1
<Greenlet at 0x10e49f550: f(5)> 2
<Greenlet at 0x10e49f550: f(5)> 3
<Greenlet at 0x10e49f550: f(5)> 4
<Greenlet at 0x10e49f910: f(5)> 0
<Greenlet at 0x10e49f910: f(5)> 1
<Greenlet at 0x10e49f910: f(5)> 2
<Greenlet at 0x10e49f910: f(5)> 3
<Greenlet at 0x10e49f910: f(5)> 4
<Greenlet at 0x10e49f4b0: f(5)> 0
<Greenlet at 0x10e49f4b0: f(5)> 1
<Greenlet at 0x10e49f4b0: f(5)> 2
<Greenlet at 0x10e49f4b0: f(5)> 3
<Greenlet at 0x10e49f4b0: f(5)> 4
好望,3个greenlet是各个运行而休是轮番运行

  1. gevent切换执行

import gevent

def f(n):
for i in range(n):
print(gevent.getcurrent(), i)
#因此来学一个耗时操作,注意不是time模块中之sleep
gevent.sleep(1)

g1 = gevent.spawn(f, 5)
g2 = gevent.spawn(f, 5)
g3 = gevent.spawn(f, 5)
g1.join()
g2.join()
g3.join()
运转结果

<Greenlet at 0x7fa70ffa1c30: f(5)> 0
<Greenlet at 0x7fa70ffa1870: f(5)> 0
<Greenlet at 0x7fa70ffa1eb0: f(5)> 0
<Greenlet at 0x7fa70ffa1c30: f(5)> 1
<Greenlet at 0x7fa70ffa1870: f(5)> 1
<Greenlet at 0x7fa70ffa1eb0: f(5)> 1
<Greenlet at 0x7fa70ffa1c30: f(5)> 2
<Greenlet at 0x7fa70ffa1870: f(5)> 2
<Greenlet at 0x7fa70ffa1eb0: f(5)> 2
<Greenlet at 0x7fa70ffa1c30: f(5)> 3
<Greenlet at 0x7fa70ffa1870: f(5)> 3
<Greenlet at 0x7fa70ffa1eb0: f(5)> 3
<Greenlet at 0x7fa70ffa1c30: f(5)> 4
<Greenlet at 0x7fa70ffa1870: f(5)> 4
<Greenlet at 0x7fa70ffa1eb0: f(5)> 4

  1. 被程序打补丁

from gevent import monkey
import gevent
import random
import time

def coroutine_work(coroutine_name):
for i in range(10):
print(coroutine_name, i)
time.sleep(random.random())

gevent.joinall([
gevent.spawn(coroutine_work, “work1”),
gevent.spawn(coroutine_work, “work2”)
])
运行结果

work1 0
work1 1
work1 2
work1 3
work1 4
work1 5
work1 6
work1 7
work1 8
work1 9
work2 0
work2 1
work2 2
work2 3
work2 4
work2 5
work2 6
work2 7
work2 8
work2 9
from gevent import monkey
import gevent
import random
import time

发出耗时操作时得

monkey.patch_all() #
将顺序中因故到之耗时操作的代码,换吧gevent中好实现的模块

def coroutine_work(coroutine_name):
for i in range(10):
print(coroutine_name, i)
time.sleep(random.random())

gevent.joinall([
gevent.spawn(coroutine_work, “work1”),
gevent.spawn(coroutine_work, “work2”)
])
运作结果

work1 0
work2 0
work1 1
work1 2
work1 3
work2 1
work1 4
work2 2
work1 5
work2 3
work1 6
work1 7
work1 8
work2 4
work2 5
work1 9
work2 6
work2 7
work2 8
work2 9

=======================================================

初稿链接:做尽规范最懂得你的python开发者交流平台,提供你无限需要之开销上资源。
我们注意于python开发技术的修及交流,我们坚持,每天进步同样略带步,人生进步同样良步!关注【Python开发者交流平台】,与我们共上学发展。