【发布时间】:2012-10-23 22:43:25
【问题描述】:
在仔细检查 threading.Condition 是否正确修补了猴子修补程序时,我注意到猴子修补程序 threading.Thread(…).start() 的行为与 gevent.spawn(…) 不同。
考虑:
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开头的cmets。
当使用第一行(带有gevent.spawn)时,第一个thread.join() 会引发异常:
但是,Thread(…).start()(第二个区块),一切正常。
为什么会这样? gevent.spawn() 和 Thread(…).start() 有什么区别?
【问题讨论】:
标签: python multithreading gevent