欢迎访问 生活随笔!

生活随笔

当前位置: 首页 >

多协程实例讲解(四 Python)

发布时间:2025/4/16 35 豆豆
生活随笔 收集整理的这篇文章主要介绍了 多协程实例讲解(四 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 setterputs 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 setterputs 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` oruntil the optional timeout occurs.When the *timeout* argument is present and not ``None``, it should be afloating point number specifying a timeout for the operation in seconds(or fractions thereof). If the *timeout* elapses, the *Timeout* exception willbe 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._valueif self._exc_info:return self._raise_exception()if not block:# Not ready and not blocking, so immediately timeoutraise Timeout()# Wait, raising a timeout that elapsesself._wait_core(timeout, ())# by definition we are now readyreturn self.get(block=False)

总结

以上是生活随笔为你收集整理的多协程实例讲解(四 Python)的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。