在 eventlet 中使用 gevent 的 sleep 可以避免阻塞嗎?

ponponon發表於2022-07-04

不能哦!

from loguru import logger
import gevent
# from gevent import monkey
# monkey.patch_all()

import eventlet
eventlet.monkey_patch()


def foo(i):
    gevent.sleep(1)


pool = eventlet.GreenPool()
for body in pool.imap(foo, [i for i in range(2)]):
    print("got body", body)

執行結果:

╰─➤  time python eventlet_with_gevent_sleep.py 
got body None
got body None
python eventlet_with_gevent_sleep.py  0.39s user 0.05s system 17% cpu 2.515 total

可以看到,一共消耗了 2 秒多


from loguru import logger
import gevent
# from gevent import monkey
# monkey.patch_all()

import eventlet
eventlet.monkey_patch()


def foo(i):
    eventlet.sleep(1)


pool = eventlet.GreenPool()
for body in pool.imap(foo, [i for i in range(2)]):
    print("got body", body)

執行結果:

─➤  time python eventlet_with_gevent_sleep.py
got body None
got body None
python eventlet_with_gevent_sleep.py  0.41s user 0.05s system 29% cpu 1.594 total

使用 eventlet 就變成正常了

相關文章