代码:
1 import gevent 2 3 4 def f1(n): 5 for i in range(n): 6 print(gevent.getcurrent(),i) 7 gevent.sleep(1) 8 9 def f2(n): 10 for i in range(n): 11 print(gevent.getcurrent(),i) 12 gevent.sleep(0.1) 13 14 15 def f3(n): 16 for i in range(n): 17 print(gevent.getcurrent(),i) 18 gevent.sleep(0.2) 19 20 21 print("---1---") 22 # gevent比greenlet好的地方是,遇到sleep自动切换,但是不支持time.sleep(),支持gevent.sleep() 23 # 不止是sleep,但凡延时或者堵塞的东西全要换成gevent里面的 24 g1 = gevent.spawn(f1,5) 25 print("---2---") 26 g2 = gevent.spawn(f2,5) 27 print("---3---") 28 g3 = gevent.spawn(f3,5) 29 print("---4---") 30 g1.join() 31 g2.join() 32 g3.join()
结果:
---1--- ---2--- ---3--- ---4--- <Greenlet at 0x1ba58dbc648: f1(5)> 0 <Greenlet at 0x1ba58dbc948: f2(5)> 0 <Greenlet at 0x1ba58dbca48: f3(5)> 0 <Greenlet at 0x1ba58dbc948: f2(5)> 1 <Greenlet at 0x1ba58dbca48: f3(5)> 1 <Greenlet at 0x1ba58dbc948: f2(5)> 2 <Greenlet at 0x1ba58dbc948: f2(5)> 3 <Greenlet at 0x1ba58dbca48: f3(5)> 2 <Greenlet at 0x1ba58dbc948: f2(5)> 4 <Greenlet at 0x1ba58dbca48: f3(5)> 3 <Greenlet at 0x1ba58dbca48: f3(5)> 4 <Greenlet at 0x1ba58dbc648: f1(5)> 1 <Greenlet at 0x1ba58dbc648: f1(5)> 2 <Greenlet at 0x1ba58dbc648: f1(5)> 3 <Greenlet at 0x1ba58dbc648: f1(5)> 4
这种比较麻烦,如果源代码里面用到time.sleep()或者socket中的堵塞,一个一个改会很麻烦,所以有了gevent的补丁
代码:
1 import gevent 2 import time 3 from gevent import monkey 4 5 6 monkey.patch_all() 7 8 def f1(n): 9 for i in range(n): 10 print(gevent.getcurrent(),i) 11 time.sleep(1) 12 13 14 def f2(n): 15 for i in range(n): 16 print(gevent.getcurrent(),i) 17 time.sleep(0.1) 18 19 20 def f3(n): 21 for i in range(n): 22 print(gevent.getcurrent(),i) 23 time.sleep(0.2) 24 25 26 # print("---1---") 27 # # gevent比greenlet好的地方是,遇到sleep自动切换,但是不支持time.sleep(),支持gevent.sleep() 28 # # 不止是sleep,但凡延时或者堵塞的东西全要换成gevent里面的 29 # g1 = gevent.spawn(f1,5) 30 # print("---2---") 31 # g2 = gevent.spawn(f2,5) 32 # print("---3---") 33 # g3 = gevent.spawn(f3,5) 34 # print("---4---") 35 # g1.join() 36 # g2.join() 37 # g3.join() 38 # 一个一个join()很麻烦,可以放到joinall()的列表中 39 gevent.joinall([ 40 gevent.spawn(f1,5), 41 gevent.spawn(f2,5), 42 gevent.spawn(f3,5) 43 44 ])
结果不变:
<Greenlet at 0x1a159007048: f1(5)> 0 <Greenlet at 0x1a159007248: f2(5)> 0 <Greenlet at 0x1a159007348: f3(5)> 0 <Greenlet at 0x1a159007248: f2(5)> 1 <Greenlet at 0x1a159007348: f3(5)> 1 <Greenlet at 0x1a159007248: f2(5)> 2 <Greenlet at 0x1a159007248: f2(5)> 3 <Greenlet at 0x1a159007348: f3(5)> 2 <Greenlet at 0x1a159007248: f2(5)> 4 <Greenlet at 0x1a159007348: f3(5)> 3 <Greenlet at 0x1a159007348: f3(5)> 4 <Greenlet at 0x1a159007048: f1(5)> 1 <Greenlet at 0x1a159007048: f1(5)> 2 <Greenlet at 0x1a159007048: f1(5)> 3 <Greenlet at 0x1a159007048: f1(5)> 4