深究Python中的asyncio庫 執行緒同步

2021-10-11 18:01:14 字數 1913 閱讀 4222

前面的**都是非同步的,就如sleep,需要用asyncio.sleep而不是阻塞的time.sleep,如果有同步邏輯,怎麼利用asyncio實現併發呢?答案是用run_in_executor。在一開始我說過開發者建立 future 物件情況很少,主要是用run_in_executor,就是讓同步函式在乙個執行器( executor)裡面執行。

同步**

defa(

):time.sleep(1)

return

'a'async

defb()

:await asyncio.sleep(1)

return

'b'def

show_perf

(func)

:print

('*'*20

) start = time.perf_counter(

) asyncio.run(func())

print

(f' cost: '

)async

defc1()

: loop = asyncio.get_running_loop(

)await asyncio.gather(

loop.run_in_executor(

none

, a)

, b())

in : show_perf(c1)

****

****

****

****

****

c1 cost:

1.0027242230000866

可以看到用run_into_executor可以把同步函式邏輯轉化成乙個協程,且實現了併發。這裡要注意細節,就是函式a是普通函式,不能寫成協程,下面的定義是錯誤的,不能實現併發:

async

defa()

: time.sleep(1)

return

'a'

因為 a 裡面沒有非同步**,就不要用async def來定義。需要把這種邏輯用loop.run_in_executor封裝到協程:

```python

async

defc()

: loop = asyncio.get_running_loop(

)return

await loop.run_in_executor(

none

, a)

大家理解了吧?

```python

loop.run_in_executor(none, a)這裡面第乙個引數是要傳遞concurrent.futures.executor例項的,傳遞none會選擇預設的executor:

in : loop._default_executor

out:

當然我們還可以用程序池,這次換個常用的檔案讀寫例子,並且用:

async

defc3()

: loop = asyncio.get_running_loop(

)with concurrent.futures.processpoolexecutor(

)as e:

print

(await asyncio.gather(

loop.run_in_executor(e, a)

, b())

)in : show_perf(c3)

****

****

****

****

****

['a'

,'b'

]c3 cost:

1.0218078890000015

jQuery Ajax中引數async的設定問題

利用jquery ajax向後台傳遞引數相信大家都不陌生。在這個過程中有乙個引數async表示是否非同步,它是乙個布林值,可以取true或者false,那麼這兩者之間的區別在 下面看乙個demo 測試title src lib easyui jquery.min.js script head doc...

vue 中scoped 和 deep的用法深究

前言 我們都知道在元件中給style標籤新增scoped屬性可以避免元件內樣式對外界造成汙染,scoped使得元件內的樣式變成局域樣式,只作用於當前元件。這個是怎麼做到的呢?原理在編譯元件的時候,如果當前元件內style標籤上有scoped屬性,那麼會在當前所有標籤上新增乙個 data v hash...

深究 CSS中px rem與em的區別

前言 隨著pc端的網頁盛行,移動端作為重要的一部分,也是火熱的發展,但是鑑於一些單位的使用,我們並不知道該怎樣去使用,那麼今天我們來看看常用的三種單位px rem與em。二.em 三.rem 四.總結 px畫素 pixel 相對長度單位。畫素px是相對於顯示器螢幕解析度而言的。px px是pixel...