Skip to content

Instantly share code, notes, and snippets.

@samspills
Last active January 24, 2023 22:06
Show Gist options
  • Save samspills/9ffe669e9f71ae919c9962b68f53f130 to your computer and use it in GitHub Desktop.
Save samspills/9ffe669e9f71ae919c9962b68f53f130 to your computer and use it in GitHub Desktop.
many ref updates
//> using lib "org.typelevel::cats-effect:3.4.5"
import cats.effect.{IO, IOApp, Sync}
import cats.effect.kernel.Ref
import cats.syntax.all._
class Worker[F[_]](id: Int, ref: Ref[F, Int])(implicit F: Sync[F]) {
private def putStrLn(value: String): F[Unit] =
F.blocking(println(value))
def start: F[Unit] =
for {
c1 <- ref.get
_ <- putStrLn(show"Worker #$id >> $c1")
c2 <- ref.updateAndGet(x => x + 1)
_ <- putStrLn(show"Worker #$id >> $c2")
} yield ()
}
object RefExample extends IOApp.Simple {
val run: IO[Unit] =
for {
ref <- Ref[IO].of(0)
w1 = new Worker[IO](1, ref)
w2 = new Worker[IO](2, ref)
w3 = new Worker[IO](3, ref)
_ <- List(
w1.start,
w2.start,
w3.start,
w1.start,
w2.start,
w3.start,
w1.start,
w2.start,
w3.start,
w1.start,
w2.start,
w3.start,
w1.start,
w2.start,
w3.start,
w1.start,
w2.start,
w3.start,
w1.start,
w2.start,
w3.start,
w1.start,
w2.start,
w3.start,
w1.start,
w2.start,
w3.start,
w1.start,
w2.start,
w3.start,
w1.start,
w2.start,
w3.start,
w1.start,
w2.start,
w3.start,
w1.start,
w2.start,
w3.start,
w1.start,
w2.start,
w3.start,
w1.start,
w2.start,
w3.start,
w1.start,
w2.start,
w3.start,
w1.start,
w2.start,
w3.start,
).parSequence.void
} yield ()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment