Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure best way to achieve multiple threads?

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?

like image 492
Timothy McDowell Avatar asked Mar 30 '10 19:03

Timothy McDowell


People also ask

Why choose Clojure for multi-threaded programming?

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.

What is the best practice for multi threading in Java?

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.

What are thread-first macros in Clojure?

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:

Why are role models important in Clojure programming?

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.


1 Answers

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

like image 100
Tim Harper Avatar answered Oct 23 '22 01:10

Tim Harper