雖然仔細檢查了threading.Condition
是否正確修補了猴子,但我注意到monkeypatched threading.Thread(…).start()
的行爲與gevent.spawn(…)
的行爲不同。爲什麼`gevent.spawn`不同於monkeypatched`threading.Thread()`?
考慮:
from gevent import monkey; monkey.patch_all()
from threading import Thread, Condition
import gevent
cv = Condition()
def wait_on_cv(x):
cv.acquire()
cv.wait()
print "Here:", x
cv.release()
# XXX: This code yields "This operation would block forever" when joining the first thread
threads = [ gevent.spawn(wait_on_cv, x) for x in range(10) ]
"""
# XXX: This code, which seems semantically similar, works correctly
threads = [ Thread(target=wait_on_cv, args=(x,)) for x in range(10) ]
for t in threads:
t.start()
"""
cv.acquire()
cv.notify_all()
print "Notified!"
cv.release()
for x, thread in enumerate(threads):
print "Joining", x
thread.join()
注意,特別是,這兩個意見開始XXX
。
當使用所述第一線(帶gevent.spawn
),所述第一thread.join()
引發一個例外:
Notified! Joining 0 Traceback (most recent call last): File "foo.py", line 30, in thread.join() File "…/gevent/greenlet.py", line 291, in join result = self.parent.switch() File "…/gevent/hub.py", line 381, in switch return greenlet.switch(self) gevent.hub.LoopExit: This operation would block forever
然而,Thread(…).start()
(第二塊),一切都按預期工作。
這是爲什麼? gevent.spawn()
和Thread(…).start()
有什麼區別?