0

I have read that functional programming is pretty well suited for multithreaded programs given the programming language paradigms it brings (immutability, side effect-free functions). I have also read that multithreaded programs are often non nondeterministic.

Given stakx answer to a similar (but different) question, here is my question:

Can a multithreaded program be deterministic if coded using functional programming languages?

Community
  • 1
  • 1
Fantastic
  • 13
  • 3
  • This question seems to imply that a multithreaded program, regardless of the language in which it is written, is typically not deterministic. Why? – Matt Ball Dec 24 '14 at 03:50
  • Because when you have 20 threads running concurrently, you can't really be sure of the output 100% of the time given the same input? – Fantastic Dec 24 '14 at 03:53

1 Answers1

0

Of course. Any program can be made deterministic. For example,

Thread.new do
  1 + 2
end
Thread.new do
  2 + 3
end

is deterministic, as it does not affect the universe in any fashion. It is all in the way you order your side-effects. If you have no mutable structures, it is then only the matter of ordering your input-output and interprocess communication predictably. But if you are asking if every functional program is deterministic, the answer is no: the moment your threads communicate or do IO, you need some explicit scheduling to make it work the same each time.

Amadan
  • 191,408
  • 23
  • 240
  • 301
  • Yes, of course trivial examples can be made deterministic easily. I think I meant "every functional programs". Thanks for the clarification anyways – Fantastic Dec 24 '14 at 03:58
  • Yeah; typically the only source of nondeterminism is side effects. Mutating state is one such, and it gets eliminated or restricted in many functional languages. But IO is nothing but a side-effect; the moment you write something out, whether to stdout or to another thread - or read something in - you are introducing side-effects, and unless you explicitly orchestrate them, you get the same non-determinism as in the imperative world. – Amadan Dec 24 '14 at 04:22