谷歌应用程序引擎——异步代码块?蟒蛇



所以我有一些代码的功能类似于以下通用代码:

for blah in blahs:
   blah.take_forever()
for blah2 in blah2s:
  vars = blah2.take_forever()
  for var in vars:
     var.also_take_forever()

我想要一些类似异步的东西,比如

async_start_blah2_loop_then_do_someting_else()
do_the_first_blah_loop()
gather_results_and_send_them_out()

然而,我并没有使用数据存储或urlfetch,那么还有什么其他选项可以加快这个过程呢?

"

map_async(callback, pass_batch_into_callback=None, merge_future=None, **q_options)
Asynchronously map a callback function or tasklet over the query results. This is the asynchronous version of map().

"

似乎只适用于数据存储查询。

建议?

您可以在App Engine中使用Python的本地线程模块异步执行函数(请参阅threading.Thread)。这在自动缩放的实例上也很好,因为它使用"绿色"线程而不是OS线程。

def blahFunc():
  for blah in blahs:
    blah.take_forever()
def blah2Func():
  for blah2 in blah2s:
    vars = blah2.take_forever()
    for var in vars:
      var.also_take_forever()
# Execute both loops 'at the same time'
background = threading.Thread(target=blah2Func)
background.start() 
blah1Func()

请注意,您不一定会从中获得任何速度(为了简单起见,我认为您的请求是一个人为的例子),因为请求仍然在同一个"真实"操作系统线程内执行,但如果您需要避免长操作上的阻塞,这是很有用的。

如果您有运行时间很长的任务,可能需要比请求运行时间更长,那么更好的解决方案是使用任务队列。

最新更新