Skip to content

Instantly share code, notes, and snippets.

@valentiay
Last active October 3, 2019 09:47
Show Gist options
  • Save valentiay/912d3070c659d742f2f97e0d17d8427a to your computer and use it in GitHub Desktop.
Save valentiay/912d3070c659d742f2f97e0d17d8427a to your computer and use it in GitHub Desktop.
import scala.util.Random
import scala.concurrent.duration._
import cats.effect.{ExitCode, IOApp, IO}
import cats.effect.concurrent.MVar
import cats.instances.list._
import cats.syntax.apply._
import cats.syntax.parallel._
object ConsensusApp extends IOApp {
class Consensus(val mvar: MVar[IO, Int]) {
def propose(value: Int): IO[Int] =
mvar.tryPut(value) *> mvar.read
}
def propose(consensus: Consensus, value: Int): IO[Int] =
for {
delay <- IO(Random.nextInt(1000))
_ <- IO.sleep(FiniteDuration.apply(delay, MILLISECONDS))
result <- consensus.propose(value)
_ <- IO(println(s"Proposed $value, got $result, delay $delay ms"))
} yield result
def run(args: List[String]): IO[ExitCode] =
for {
mvar <- MVar.empty[IO, Int]
consensus = new Consensus(mvar)
_ <- (1 to 10).toList.parTraverse(value => propose(consensus, value))
} yield ExitCode.Success
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment