Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How are functions modified at run-time then propagated to multiple threads?

With Clojure (and other Lisp dialects) you can modify running code. So, when a function is modified during runtime is that change made available to multiple threads?

I'm trying to figure out how it works technically in a concurrent setting: if several threads are using a function foo, what happens when I redefine (say using defn) the function foo?

There has to be some synchronization going on: when and how does such synchronization happen and what does it cost?

Say on a JVM, is the function referenced using a volatile reference? If so, does it mean every single time there's a "function lookup" then one has to pay the volatile cost?

like image 865
Cedric Martin Avatar asked Jun 28 '12 00:06

Cedric Martin


1 Answers

In Clojure functions are instances of the IFn class and they are almost always stored in vars. vars are Clojures mechanism for thread local values.

  • when you define a function that sets the "root binding" of the var to reference the function
  • threads other threads get whatever the the current value of the root binding for the var but can't change the value. this prevents any two threads from having to fight over the value of the var because only the root thread can set the value.
  • threads can choose to use a new value of the var if they need to, but calling binding which gives then their own thread local value that they are free to change at will because no other thread can read it.

A good understanding of vars is well worth a little study, they are a very useful concurrency device once you get used to them.

ps: the root thread is usually the REPL pss: you are of course free to store your functions in something other than vars, if for instance you needed to atomically update a group of functions, though this is rare.

like image 96
Arthur Ulfeldt Avatar answered Oct 11 '22 22:10

Arthur Ulfeldt