Concurrency
and the Laws of Physics
What is concurrency?
- Things happen at the same time
- Things happen in any order
Vending machine
Vending machine
Queuing people
Processor
Threads
Reasoning
- Tests
- Looking at the code 🤯
- Formal verification
Laws
- Causality: If B happened, it happened after A
- Determinism: If A happens, B must happen
- Observation: Events must be observed at the same point in space
Enforcing laws
- Substitution
- IO
- Resource
- Typeclasses
What happens first?
1 + 2 + 3 + 4
1 + 2 + 3 + 4
(1 + 2) + (3 + 4)
3 + 7
10
It doesn't matter
1 + 2 + 3 + 4
(1 + 2) + 3 + 4
(3 + 3) + 4
6 + 4
10
IO
Stream(1)
.repeat
.debug()
.take(3)
.compile
.toList
Stream.eval(IO.pure(1))
.repeat
.debug()
.take(3)
.compile
.toList
.unsafeRunSync()
IO
Stream(1)
.repeat
.debug()
.take(3)
.compile
.drain
Stream.eval(IO.pure(1))
.repeat
.debug()
.take(3)
.compile
.drain
.unsafeRunSync()
1
1
1
1
1
1
1
What happens first?
IO.println("Hello") >> IO.println("world")
Causality
If B happened, it happened after A
Enforced by IO
Does it always happen?
IO.println("Hello") >> IO.println("world")
val program = IO.println("Hello") >> IO.println("world")
val fiber = program.start
fiber >>= (_.cancel)
val program = Resource.make(IO.println("Hello")) { _ =>
IO.println("world")
}
resource.use { program =>
val fiber = program.start
fiber >>= (_.cancel)
}
Resource
Determinism
 If A happens, B must happen
Enforced with resources
Many other utilities
- Typeclasses: Sync, Concurrent
- State management: Ref
- Concurrency primitives: Queues
Thank you!
Copy of Concurrency and the Laws of Physics
By Zainab Ali
Copy of Concurrency and the Laws of Physics
- 305