3

基本思路如下:

一个请求来了views1,它首先返回用户名。do_something_else在views1完成后,有一些繁重的工作需要单独完成。您可以将其视为创建一个新用户,但必须对后台进行一些繁重的检查。

def views1(..):
   username = get_uername(...)
   return username

from lib import do_something_else
def do_something_else(...):
   // do heavy stuff here

gevent.joinall([
   gevent.spawn(views1, parmeter1, parmeter2, ...),
   gevent.spawn(do_something_else, parmeter1, parmeter2, ...)
])

问题是我不认为do_something_else根据我的日志记录被调用过。我读了教程,我不知道该放在哪里gevent.sleep(0)。我不想阻塞。我希望用户立即看到用户名,并do_something_else在后台运行。

任何想法?

4

1 回答 1

3

重要的是要了解您需要将“重负载”处理分离到线程池 [1]。

在 gevent 线程中发生的每个处理(每个本地线程可以有一个 gevent HUB)必须只专注于处理网络请求和发送响应。

from gevent import spawn, run
from gevent.threadpool import ThreadPool
from time import sleep as heavy_load, time as now

class Globals:
    jobs = 4
    index = 0
    greenlets = []
    pool = ThreadPool(3) # change size of the pool appropriately

start = now()

def get_uername():
    heavy_load(0.1)
    Globals.index += 1
    return "Alex {0}".format(Globals.index)

def do_something_else(username):
    heavy_load(2.0)
    print "Heavy job done for", username, now() - start

def views1():
    "a request comes to views1 and it first returns the username"
    username = get_uername()
    ## There is some heavy job separate done by do_something_else right after views1 is done
    Globals.greenlets.append( 
        Globals.pool.spawn(do_something_else, username) 
        )
    # return username
    print "Returned requested username", username, now() - start


if __name__ == '__main__':
    ## simulate clients 
    for job_index in xrange(Globals.jobs):
        Globals.greenlets.append( spawn(views1) )

    ## wait for all tasks to complete
    # for greenlet in Globals.greenlets:
        # try:
            # greenlet.join()
        # except AttributeError, e:
            # greenlet.get()
    run()
    print "Test done", now() - start

这是测试的输出:

python threadpool_test.py
Returned requested username Alex 1 0.101000070572
Returned requested username Alex 2 0.201999902725
Returned requested username Alex 3 0.302999973297
Returned requested username Alex 4 0.40299987793
Heavy job done for Alex 1 2.10100007057
Heavy job done for Alex 2 2.2009999752
Heavy job done for Alex 3 2.3029999733
Heavy job done for Alex 4 4.10299992561
Test done 4.10500001907

注意所有请求是如何首先完成的,并行do_something_else任务是如何分批完成的,大小为 3。

当不使用 ThreadPool 时,每个请求都会花费由 gevent 引入的额外时间,do_something_else而这并不是asynchronous programminggevent 必须提供的。在这种情况下,输出将如下所示:

Heavy job done for Alex 1 2.10100007057
Returned requested username Alex 1 2.10100007057
Heavy job done for Alex 2 4.2009999752
Returned requested username Alex 2 4.20199990273
Heavy job done for Alex 3 6.30200004578
Returned requested username Alex 3 6.3029999733
Heavy job done for Alex 4 8.40299987793
Returned requested username Alex 4 8.40400004387
Test done 8.40400004387

注意第四个请求是如何在 8.4 秒后完成的,而不是在异步处理时 0.4 秒。

[1] http://code.google.com/p/gevent/source/browse/examples/threadpool.py

于 2012-07-23T10:16:11.477 回答