简体   繁体   English

为什么gevent执行这个未加入的greenlet?

[英]Why does gevent execute this unjoined greenlet?

Code: 码:

import gevent
import time

def func(a, t):
  time.sleep(t)
  print "got here", a

gevent.spawn(func, 'a', 4)
gevent.spawn(func, 'b', 0).join()
time.sleep(3)
print "exit"

Output: 输出:

got here a
got here b
exit

Expectation: 期望:

I never join on the first greenlet, so I expect that it will never execute; 我从不加入第一个greenlet,所以我希望它永远不会执行; or, given the long sleep(), it should complete after the second greenlet. 或者,如果长睡眠(),它应该在第二个greenlet之后完成。

Context: 语境:

I would like to be able to fire off a "throwaway" greenlet that populates a cache which I never join on and I never want to block to wait for the result of. 我希望能够启动一个“一次性”greenlet填充缓存,我永远不会加入,我永远不想阻止等待结果。

This is because time.sleep() isn't gevent-aware, so when join() is called, the execution flow will be: 这是因为time.sleep time.sleep()不是gevent-aware,所以当调用join()时,执行流将是:

  1. gevent.spawn(a) — pushes a "spawn a" operation onto the event queue gevent.spawn(a) - 将“spawn a”操作推送到事件队列
  2. gevent.spawn(b) — pushes a "spawn b" operation onto the event queue gevent.spawn(b) - 将“spawn b”操作推送到事件队列
  3. .join() — causes the main thread to yield and next event in the event queue is executed (in this case, a ) .join() - 导致主线.join()并执行事件队列中的下一个事件(在本例中为a
  4. a executes time.sleep(4) , blocking the entire process for 4 seconds (but thread a doesn't yield because time.sleep() isn't gevent-aware) a执行time.sleep(4) ,阻塞整个进程4秒(但是由于time.sleep time.sleep()不是gevent-aware,所以线程a不会产生)
  5. a terminates and the next event in the event queue is executed (in this case, b ) a终止并执行事件队列中的下一个事件(在本例中为b
  6. b executes and terminates, and the next event on the queue is executed (in this case, jumping back into the main thread, causing the .join() to return) b执行并终止,并执行队列中的下一个事件(在这种情况下,跳回主线程,导致.join()返回)

Use either gevent.monkey or gevent.sleep() to see this perform as you'd expect. 使用gevent.monkeygevent.sleep()来查看此操作是否符合您的预期。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM