Last active
February 17, 2020 17:20
-
-
Save amitayh/fad4244951067564782060dfeaebb00e to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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