简体   繁体   English

除非waitall(),为什么greenpool不会在spawn_n之后调用func?

[英]Why doesn't eventlet GreenPool call func after spawn_n unless waitall()?

This code prints nothing: 此代码不打印任何内容

def foo(i):
    print i

def main():
    pool = eventlet.GreenPool(size=100)
    for i in xrange(100):
        pool.spawn_n(foo, i)
    while True:
        pass

But this code prints numbers: 但是此代码打印数字:

def foo(i):
    print i

def main():
    pool = eventlet.GreenPool(size=100)
    for i in xrange(100):
        pool.spawn_n(foo, i)
    pool.waitall()
    while True:
        pass

The only difference is pool.waitall() . 唯一的区别是pool.waitall() In my mind, waitall() means wait until all greenthreads in the pool are finished working, but an infinite loop waits for every greenthread, so pool.waitall() is not necessary. 在我看来, waitall()意味着等到池中的所有greenthread都完成了工作,但是无限循环等待每个greenthread,所以pool.waitall()不是必需的。

So why does this happen? 那么为什么会这样呢?

Reference: http://eventlet.net/doc/modules/greenpool.html#eventlet.greenpool.GreenPool.waitall 参考: http//eventlet.net/doc/modules/greenpool.html#eventlet.greenpool.GreenPool.waitall

The threads created in an eventlet GreenPool are green threads . 在Eventlet GreenPool中创建的线程是绿色线程 This means that they all exist within one thread at the operating-system level, and the Python interpreter handles switching between them. 这意味着它们都存在于操作系统级别的一个线程中,并且Python解释器处理它们之间的切换。 This switching can only happen when one thread either yields (deliberately provides an opportunity for other threads to run) or is waiting for I/O. 这种切换只能在一个线程产生 (故意为其他线程运行的机会)或正在等待I / O时发生。

When your code runs: 代码运行时:

while True:
    pass

… that thread of execution is blocked – stuck on that code – and no other green threads can get scheduled. ...执行线程被阻止 - 卡在该代码上 - 并且没有其他绿色线程可以被安排。

When you instead run: 当您改为运行时:

pool.waitall()

… eventlet makes sure that it yields while waiting. ... eventlet确保它在等待时产生。

You could emulate this same behaviour by modifying your while loop slightly to call the eventlet.sleep function, which yields: 您可以通过稍微修改while循环来调用eventlet.sleep函数来模拟相同的行为,这会产生:

while True:
    eventlet.sleep()

This could be useful if you wanted to do something else in the while True: loop while waiting for the threads in your pool to complete. 如果您希望在等待池中的线程完成时在while True: while循环中执行其他操作,这可能很有用。 Otherwise, just use pool.waitall() – that's what it's for. 否则,只需使用pool.waitall() - 这就是它的用途。

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

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