我正在学习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'
我做错了什么,如何从每个greenlet中获取价值?
最佳答案
根据你想要的http://www.gevent.org/intro.html
原文链接:https://www.f2er.com/python/438740.htmldef asynchronous():
threads = [Greenlet.spawn(fetch,i) for i in range(10)]
result = gevent.joinall(threads)
print [thread.value for thread in threads]