我正在学习Gevent,但无法获得greenlet中调用的函数返回的值。以下代码:
import gevent.monkey
gevent.monkey.patch_socket()
import gevent
from gevent import Greenlet
import urllib2
import simplejson as json
def fetch(pid):
response = urllib2.urlopen('http://time.jsontest.com')
result = response.read()
json_result = json.loads(result)
datetime = json_result['time']
print('Process %s: %s' % (pid, datetime))
return json_result['time']
def synchronous():
for i in range(1,10):
fetch(i)
def asynchronous():
threads = [Greenlet.spawn(fetch, i) for i in range(10)]
result = gevent.joinall(threads)
print [Greenlet.value(thread) for thread in threads]
print('Synchronous:')
synchronous()
print('Asynchronous:')
asynchronous()
给我一个错误:
print [Greenlet.value(thread) for thread in threads]
AttributeError: type object 'Greenlet' has no attribute 'value'
我做错了什么?我如何从每个绿绿灯中获得价值?
根据http://www.gevent.org/intro.html你想要
def asynchronous():
threads = [Greenlet.spawn(fetch, i) for i in range(10)]
gevent.joinall(threads)
print([thread.value for thread in threads])