How do functions change at runtime and then propagate to multiple threads?

With Clojure (and other Lisp dialects), you can change the current code. So, when a function is changed at runtime, is that change made available to multiple threads?

I'm trying to understand how this works technically in parallel setup: if multiple threads use the foo function, what happens when I redefine (say, using defn) the foo function?

There must be some kind of synchronization: when and how does such synchronization take place and what does it cost?

Tell the JVM, is a function a volatile reference? If so, does this mean that every time there is a โ€œfunction searchโ€, then you need to pay volatile cost?

+6
source share
1 answer

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

  • when you define a function that sets the "root binding" var to reference the function
  • threads of other threads receive any current root binding value for var, but cannot change the value. this prevents the need for any two threads to fight for the var value, because only the root thread can set the value.
  • threads can select a new var value if necessary, but call binding , which then gives its own value to the local value of the stream , which they can change as they see fit, because no other thread can read it.

A good understanding of vars is well worth a little research, they are very useful concurrency as soon as you get used to them.

ps: the root stream is usually REPL pss: of course you can store your functions in something other than vars if, for example, you needed to atomize a group of functions, although this is rare.

+8
source

Source: https://habr.com/ru/post/919197/


All Articles