2

I'm fairly new to Clojure and LISPs in general, so excuse me in advance if this question sounds a bit silly. I've recently created a turn-based videogame in Java in a MVC fashion, with a thread in charge of the graphic loop (so, updating the geometric state of graphic entities on screen at a fixed rate), and a second thread in charge of handling the logic state of the game; it acted pretty much like a daemon: "sleeping" in the background unless requested to do something (elaborate user input), and then delivering a "change log" to the graphic thread so that it could render the changes made to the logic state. So the game world was not "shared" at all: only the logic thread had access to it, and the graphic thread's only duty was to apply changes to the rendering after an initialization phase and when a new a changed log arrived from the logic thread.

I read that Clojure has vars, refs and atoms. In such a scenario, which one of these identities should I use to store my game world state in the logic thread in Clojure?

pr0gma
  • 577
  • 3
  • 8
  • 18
  • 1
    take a look at this post where a state hais maintained in clojure multithreaded producer consumer flow http://stackoverflow.com/questions/8925371/clojure-producer-consumer – Alex Punnen Mar 09 '16 at 03:33

1 Answers1

4

In your case, no concurrent access is required, so any option is valid.

ref is a overshoot for this problem. var is not typically used in such a scenario (usually var rebinding is used for configurable parameters, instead of the business logic in your case). So atom should be fine.

EDIT: (elaboration on var)

var, when declared as ^:dynamic (and usually *earmuffed*), is thread-local. It can have a root binding, and each thread can rebind it to a new thread-local value. So typical uses of var you can see in clojure code repo, are *warn-on-reflection*, *unchecked-math*, etc. They mostly tune the behavior of our code somehow.

Since you have only one thread that works on the "board" data, it's OK to use var anyway, but it would look a bit weird to me. I become a bit upset when seeing a var be changed so often. :)

Davyzhu
  • 1,109
  • 9
  • 17
  • Hi, thanks for your reply. Could you elaborate a bit more on vars being mainly used for configurable parameters? Also, would you always suggest atoms as the way to go when dealing with mutability with no concurrent access on the same resources? – pr0gma Mar 08 '16 at 17:48
  • @pr0gma I've updated the answer. Oh, for the extra question, I wouldn't say always. Clojure 1.7 when introducing transducers, also brought in a new construct `volatile!`, it's a more light-weight construct than `atom` and is mostly used for "transient" mutable data that is not shared among threads. – Davyzhu Mar 09 '16 at 03:25
  • I didn't know about the volatile! construct, it definitely looks worth inquiring about. Thanks again for taking your time to make it clearer! – pr0gma Mar 09 '16 at 08:55