多协程实例讲解(四 Python)

还是基于官方文档进行改写的结果

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)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

肥宅_Sean

公众号“肥宅Sean”欢迎关注

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值