19

Don't quite understand determinism in the context of concurrency and parallelism in Haskell. Some examples would be helpful. Thanks

vis
  • 2,279
  • 1
  • 19
  • 27

2 Answers2

25

When dealing with pure values, the order of evaluation does not matter. That is essentially what parallelism does: Evaluating pure values in parallel. As opposed to pure values, order usually matters for actions with side-effects. Running actions simultaneously is called concurrency.

As an example, consider the two actions putStr "foo" and putStr "bar". Depending on the order in which those two actions get evaluated, the output is either "foobar", "barfoo" or any state in between. The output is indeterministic as it depends on the specific order of evaluation.

As another example, consider the two values sum [1..10] and 5 * 3. Regardless of the order in which those two get evaluated, they always reduce to the same results. This determinism is something you can usually only guarantee with pure values.

Daniel Fischer
  • 181,706
  • 17
  • 308
  • 431
fuz
  • 88,405
  • 25
  • 200
  • 352
  • 22
    +1; in other words, parallelism is an optimisation; concurrency changes semantics. – ehird Dec 20 '11 at 22:20
  • In lang oz : 1 dataflow value can only be bind one time 2 program use unbind value should be waiting until it was bind . So the behavior is determinstic when two thread use one same dataflow value . – jiamo Apr 24 '14 at 16:19
25

Concurrency and parallelism are two different things.

Concurrency means that you have multiple threads interacting non-deterministically. For example, you might have a chat server where each client is handled by one thread. The non-determinism is essential to the system you're trying to model.

Parallelism is about using multiple threads for simply making your program run faster. However, the end result should be exactly the same as if you run the algorithm sequentially.

Many languages don't have primitives for parallelism, so you have to implement it using concurrency primitives like threads and locks. However, this means that you the programmer have to be careful to ensure that you don't accidentally introduce unwanted non-determinism or other concurrency issues. With explicit parallelism primitives like par and pseq, many of these concerns simply go away.

hammar
  • 138,522
  • 17
  • 304
  • 385
  • Concurrency doesn't have to involve multiple threads, an event-loop can be used to provide concurrency in a single-threaded environment (JavaScript is one example). – ximo Jan 18 '22 at 11:06