- Hands-On Reactive Programming with Clojure
- Konrad Szydlo Leonardo Borges
- 295字
- 2021-07-02 14:03:59
Fixed buffer
This is the simplest form of buffering. It is fixed to a chosen number, n, allowing producers to put items in the channel without having to wait for consumers:
(def result (chan (async/buffer 5))) (go-loop [] (<! (async/timeout 1000)) (when-let [x (<! result)] (prn "Got value: " x) (recur))) (go (doseq [n (range 5)] (>! result n)) (prn "Done putting values!") (async/close! result)) ;; "Done putting values!" ;; "Got value: " 0 ;; "Got value: " 1 ;; "Got value: " 2 ;; "Got value: " 3 ;; "Got value: " 4
In the preceding example, we created a buffer of size 5 and started a go loop to consume values from it. The go loop uses a timeout channel to delay each loop cycle.
Then, we started another go block that puts numbers from 0 to 4 into the result channel and prints to the console once it's done.
By then, the first timeout will have expired and we will see the values printed to the REPL.
Now, let's watch what happens if the buffer isn't large enough:
(def result (chan (async/buffer 2))) (go-loop [] (<! (async/timeout 1000)) (when-let [x (<! result)] (prn "Got value: " x) (recur))) (go (doseq [n (range 5)] (>! result n)) (prn "Done putting values!") (async/close! result)) ;; "Got value: " 0 ;; "Got value: " 1 ;; "Got value: " 2 ;; "Done putting values!" ;; "Got value: " 3 ;; "Got value: " 4
This time, our buffer size is 2, but everything else is the same. As you can see, the go loop finishes much later, as it attempted to put another value in the result channel and was blocked/parked, since its buffer was full.
As with most things, this might be OK, but if we are not willing to block a fast producer just because we can't consume its items fast enough, we must look for another option.
- 兒童心理障礙診療學(xué)
- 實(shí)用口腔正畸臨床技術(shù)圖譜
- 常用運(yùn)動(dòng)損傷理療技術(shù)操作手冊(cè)
- 腦血管病的防與治
- 食品毒理學(xué)
- 腦卒中預(yù)防與控制
- 五官科疾病中西醫(yī)結(jié)合護(hù)理
- 實(shí)用胃腸病臨床手冊(cè)
- 新生兒聽(tīng)力篩查
- 會(huì)保養(yǎng)的女人年輕20歲
- 常見(jiàn)惡性腫瘤治療原則與實(shí)施方案
- 骨骼肌靜力性負(fù)荷所致?lián)p傷機(jī)理的研究
- 結(jié)核病診斷與防治技術(shù)
- 運(yùn)動(dòng)創(chuàng)傷學(xué)
- 腦卒中診療與康復(fù)問(wèn)答