From 356d48f3baf71ccb57a73d22651485aa4c6c63b4 Mon Sep 17 00:00:00 2001 From: eltrac Date: Mon, 12 Oct 2026 13:42:44 +0800 Subject: [draft] update --- content/article/clj7.md | 46 +++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 45 insertions(+), 1 deletion(-) diff --git a/content/article/clj7.md b/content/article/clj7.md index 5d709615..500900ba 100644 --- a/content/article/clj7.md +++ b/content/article/clj7.md @@ -1,6 +1,6 @@ +++ title = 'Coffee Break Clojure, Async' -subtitle = '异步编程和并发编程' +subtitle = '异步编程和并发控制' slug = '' tags = [] categories = '茶歇蔻芥' @@ -228,6 +228,50 @@ user=> (time (doall (pmap long-running-job (range 4)))) ## Gopher?是你吗? +命名空间 `clojure.core.async` 提供了另外一种异步编程的方式,但没有放在标准库里,必须要添加依赖才能使用。 + +```clojure +;; deps.edn +org.clojure/core.async {:mvn/version "1.9.865"} +;; leiningen +[org.clojure/core.async "1.9.865"] +``` + +`core.async` 几乎和 Go 语言异步编程的要素一模一样,尤其是 `go` block——把语句放在 `go` block 里面,语句就会异步执行。把消息队列 `chan` 当作一等公民的做法,也如出一辙。根据 [Clojure 官方的博客文章](https://clojure.org/news/2013/06/28/clojure-clore-async-channels),这种异步编程风格其实一段历史了,Go 也是借鉴并现代化了这种做法。 + +> The roots of this style go back at least as far as Hoare’s Communicating Sequential Processes (CSP), followed by realizations and extensions in e.g. occam, Java CSP and the Go programming language. + +无论如何,让我们来看看怎么用 `go` 和 `chan` 实现异步编程吧。如果你已经会写 Go,那么接下来的代码会很熟悉。 + +```clojure +(require '[clojure.core.async :refer [go chan >! ! queue))) +``` + +`chan` 函数用于创建 *channel*(频道),可以理解为消息队列。对于 *channel*,有放(put)和拿(take)的操作,分别用 `>!`(放)和 `!! semaphore true)) +``` + ## Footnotes [^1]: 不过其实也可以给 `agent` 发这样的函数:`(fn [_] "new value")` -- cgit v1.2.3