何时在Gevent中使用Threadpool [英] When to use Threadpool in Gevent

查看:89
本文介绍了何时在Gevent中使用Threadpool的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到Gevent具有线程池对象.有人可以向我解释何时使用线程池以及何时使用常规池吗?gevent.threadpool和gevent.pool有什么区别?

I've noticed that Gevent has threadpool object. Can someone explain to me when to use threadpool and when to use regular pool? Whats the difference between gevent.threadpool and gevent.pool?

推荐答案

当您有一段需要长时间运行(几秒钟)并且不会导致切换greenlets的python代码时,所有其他greenlets/gevent作业将饿死"并且没有计算时间,并且看起来您的应用程序挂起".

When you have a piece of python code that takes a long time to run (for seconds) and does not cause switching of greenlets, all other greenlets / gevent jobs will 'starve' and have no computation time and it will look like your application 'hangs'.

如果将这个繁重的"任务放在Threadpool中,则线程执行将确保其他greenlet不会饿死.但是我相信,如果您的代码在C库中花费大量时间,那将没有任何效果.

If you put this 'heavy' task in a Threadpool, the threaded execution will make sure other greenlets will not starve. But I believe if your code spends a lot of time in a C library, it will have no effect.

以下是 gevent.请注意,该示例使用的是 time.sleep 而不是 gevent.sleep .

Below is an example from gevent. Note that the example uses time.sleep which blocks, instead of gevent.sleep.

提示:如果您的循环需要很长时间才能运行,则只需将gevent.sleep(0)放入循环中即可.每个绿色循环都有机会运行.慢循环中的 gevent .sleep(0)将确保其他小程序不会饿死并且应用程序显示为响应状态

TIP: If you have a loop that takes a long time to run, then you can just put in a gevent.sleep(0) in the loop. Every loop other greenlets will have a chance to run. The gevent.sleep(0) in your slow loop will make sure other greenlets will not starve and the application appears responsive

import time
import gevent
from gevent.threadpool import ThreadPool


pool = ThreadPool(3)
start = time.time()
for _ in xrange(4):
    pool.spawn(time.sleep, 1)
gevent.wait()
delay = time.time() - start
print 'Running "time.sleep(1)" 4 times with 3 threads. Should take about 2 seconds: %.3fs' % delay

这篇关于何时在Gevent中使用Threadpool的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆