还是基于官方文档进行改写的结果
import gevent
from gevent.event import AsyncResult
a = AsyncResult()
def setter():
"""
After 3 seconds set the result of a.
"""
gevent.sleep(3)
a.set('Hello!')
def waiter():
"""
After 3 seconds the get call will unblock after the setter
puts a value into the AsyncResult.
"""
print("First Here")
gevent.sleep()
print('After sleep()')
print(a.get())
gevent.joinall([
gevent.spawn(setter),
gevent.spawn(waiter),
])
输出情况:
First Here
After sleep()
Hello!
虽然一开始使用了gevent sleep() 但是waiter还是会接着进行(因为另外一个休息的时间会根据,而且同样是进行切换)
- 但还是得说一下。全局变量中的 AsyncResult之间通过set和get函数进行双方的通信。
为了测试这个复用性和是否会由于多次设置,故做以下的改写setter
def setter():
"""
After 3 seconds set the result of a.
"""
gevent.sleep(3)
a.set('Hello!')
a.set('What?')
改写成这个样子之后,输出的结果就变成了下面的这个样子了
First Here
After sleep()
What?
说明具有替换的特点!
- 将上面的setter恢复成原来的样子。然后将这个waiter做了类似的修改。
def waiter():
"""
After 3 seconds the get call will unblock after the setter
puts a value into the AsyncResult.
"""
print("First Here")
gevent.sleep()
print('After sleep()')
print(a.get())
print(a.get())
输出的结果是:
First Here
After sleep()
Hello!
Hello!
在这我认为这类的实现是通过类中的某一个变量。
查了下那个官方文档的,具体的实现是下面的样子,只是返回一个变量~
def get(self, block=True, timeout=None):
"""Return the stored value or raise the exception.
If this instance already holds a value or an exception, return or raise it immediatelly.
Otherwise, block until another greenlet calls :meth:`set` or :meth:`set_exception` or
until the optional timeout occurs.
When the *timeout* argument is present and not ``None``, it should be a
floating point number specifying a timeout for the operation in seconds
(or fractions thereof). If the *timeout* elapses, the *Timeout* exception will
be raised.
:keyword bool block: If set to ``False`` and this instance is not ready,
immediately raise a :class:`Timeout` exception.
"""
if self._value is not _NONE:
return self._value
if self._exc_info:
return self._raise_exception()
if not block:
# Not ready and not blocking, so immediately timeout
raise Timeout()
# Wait, raising a timeout that elapses
self._wait_core(timeout, ())
# by definition we are now ready
return self.get(block=False)