I am working on a MUD client written in Clojure. Right now, I need two different threads. One which receives input from the user and sends it out to the MUD (via a simple Socket), and one that reads and displays output from the MUD, to the user.
Should I just use Java Threads, or is there some Clojure-specific feature I should be turning to?
Today’s systems have to deal with many simultaneous tasks and leverage the power of multi-core CPUs. Doing so with threads can be very difficult due to the complexities of synchronization. Clojure simplifies multi-threaded programming in several ways. Because the core data structures are immutable, they can be shared readily between threads.
This Java multi-threading best practice is an extension of earlier best practices about minimizing the scope of locking. Using synchronized block is one way to reduce the scope of lock and it also allows you to lock on an object other than "this", which represents the current object.
Threading macros, also known as arrow macros, convert nested function calls into a linear flow of function calls, improving readability. The thread-first macro (->) In idiomatic Clojure, pure functions transform immutable data structures into a desired output format. Consider a function that applies two transformations to a map:
Role models are important. This Clojure style guide recommends best practices so that real-world Clojure programmers can write code that can be maintained by other real-world Clojure programmers.
I would recommend using the pcalls function, like this:
(defn- process-server-responses []
(prn "server connected")
(. java.lang.Thread sleep 1000)
(prn "server disconnected"))
(defn- process-client-input []
(prn "client-input start")
(. java.lang.Thread sleep 1000)
(prn "client-input stop"))
(pcalls process-server-responses process-client-input)
Output for the above:
"server connected"
"client-input start"
"server disconnected"
"client-input stop"
Docs for pcalls here:
http://richhickey.github.com/clojure/clojure.core-api.html#clojure.core/pcalls
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With