Chinaunix首页 | 论坛 | 博客
  • 博客访问: 4469249
  • 博文数量: 1214
  • 博客积分: 13195
  • 博客等级: 上将
  • 技术积分: 9105
  • 用 户 组: 普通用户
  • 注册时间: 2007-01-19 14:41
个人简介

C++,python,热爱算法和机器学习

文章分类

全部博文(1214)

文章存档

2021年(13)

2020年(49)

2019年(14)

2018年(27)

2017年(69)

2016年(100)

2015年(106)

2014年(240)

2013年(5)

2012年(193)

2011年(155)

2010年(93)

2009年(62)

2008年(51)

2007年(37)

分类: Python/Ruby

2015-01-04 12:40:34

Gevent can spawn a co-routine: g1 = gevent.spawn(function)
After the function is been called, g1 has its return value: g1.value
If we want to have a callback with g1.value: g1.rawlink(callback)
This callback will be called before join: gevent.joinall([g1])

Here is the expirement about this conclusion:
Python语言
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Yuande Liu
# gevent's rawlink(callback) are executed before gevent.join() return

from __future__ import print_function
import gevent
from gevent.pool import Pool
p = Pool(100)

alist = []

def return_self(x):
   return x

def callback(greenlet):
   """
   If we call `gevent.sleep(0)` in this callback:
       AssertionError: Impossible to call blocking function in the event loop callback
   """
   global alist
   alist.append( greenlet.value )
   2**2**20 # about 2s in Intel i5 2.4GHz

def run():
   for x in xrange(10000):
       b = p.spawn(return_self, x)
       b.rawlink(callback)

   global alist
   print('before join alist: {}'.format(len(alist)))
   p.join()
   print('after join alist: {}'.format(len(alist)))

run()
print('alist: {}'.format(len(alist)))


结果:

before join alist: 9900

after join alist: 10000

alist: 10000


阅读之后,发现确实是这样。
阅读(832) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~