Last active
January 24, 2023 22:06
-
-
Save samspills/9ffe669e9f71ae919c9962b68f53f130 to your computer and use it in GitHub Desktop.
many ref updates
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//> 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