日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

多协程实例讲解(四 Python)

發布時間:2025/4/16 python 14 豆豆
生活随笔 收集整理的這篇文章主要介紹了 多协程实例讲解(四 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)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。