Skip to content

Instantly share code, notes, and snippets.

@amitayh
Last active February 17, 2020 17:20
Show Gist options
  • Save amitayh/fad4244951067564782060dfeaebb00e to your computer and use it in GitHub Desktop.
Save amitayh/fad4244951067564782060dfeaebb00e to your computer and use it in GitHub Desktop.
import cats.Applicative
import cats.effect.Concurrent
import cats.effect.concurrent.{Deferred, Ref}
import cats.syntax.flatMap._
import cats.syntax.functor._
trait CountDownLatch[F[_]] {
def countDown: F[Unit]
def await: F[Unit]
}
object CountDownLatch {
def apply[F[_]: Concurrent](count: Int): F[CountDownLatch[F]] = for {
ref <- Ref.of[F, Int](count)
ready <- Deferred[F, Unit]
} yield new CountDownLatch[F] {
override def countDown: F[Unit] =
ref.modify(current => (current - 1, current - 1)).flatMap {
case 0 => ready.complete(())
case _ => Applicative[F].unit
}
override def await: F[Unit] = ready.get
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment