Skip to content

Instantly share code, notes, and snippets.

@eldritchideen
Last active June 25, 2023 01:04
Show Gist options
  • Save eldritchideen/89b9ba06457b568f0d1a to your computer and use it in GitHub Desktop.
Save eldritchideen/89b9ba06457b568f0d1a to your computer and use it in GitHub Desktop.
Very simple actor implementation with core.async
(ns scratch.core
(:require [clojure.core.async :as async :refer [go-loop <! chan <!! >! >!!]])
(:gen-class))
(defn make-actor
"Creates actor of specific name" [name]
(let [in (chan 10)]
(go-loop [[msg-type sender msg-body :as data] (<! in)]
(when data
(println (str "Actor " name " got message " msg-type
" from " sender " with content " msg-body))
(>! sender (str name " got message " msg-type))
(recur (<! in))))
in))
; REPL testing
;(def a1 (make-actor "actor1"))
;=> (var scratch.core/a1)
;(def a2 (make-actor "actor2"))
;=> (var scratch.core/a2)
;(def repl-in-box (async/chan 10))
;=> (var scratch.core/repl-in-box)
;(async/>!! a1 [:foo repl-in-box "xxxyyyzzz"])
;=> true
;Actor actor1 got message :foo from clojure.core.async.impl.channels.ManyToManyChannel@77812e2f with content xxxyyyzzz
;(async/>!! a2 [:bar repl-in-box "aaaaaaaaaaaa"])
;=> true
;Actor actor2 got message :bar from clojure.core.async.impl.channels.ManyToManyChannel@77812e2f with content aaaaaaaaaaaa
;(async/<!! repl-in-box)
;=> "actor1 got message :foo"
;(async/<!! repl-in-box)
;=> "actor2 got message :bar"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment