cats-effect icon indicating copy to clipboard operation
cats-effect copied to clipboard

Document that Fibers can close over non-volatile vars

Open otto-dev opened this issue 4 years ago • 1 comments
trafficstars

a fiber can close over a non volatile var safely we should add it to the docs because it's come up a few times

:point_up:

The (hacky, non-FP) example I used to ask about this:

  def actorThatOnlyUpdatesState[F[_]: Async, S](
      initialState: F[S]
  ) = for {
    inbox <- Queue.unbounded[F, S => S]
    s <- initialState
    _ <- {
      var state = s
      inbox.take.map(f => state = f(state)).foreverM
    }.start
  } yield inbox.offer _

This loops over a Queue that contains S => S, which updates the state. I can then push S => S functions onto that queue, which will then be executed. Apparently the state = f(state) is not an issue here from a thread-safety perspective.

otto-dev avatar Nov 01 '21 13:11 otto-dev

Yep, I remember finding out about this via word-of-mouth 😆

armanbilge avatar Nov 01 '21 17:11 armanbilge