Count Down Latch
A one-shot concurrency primitive that blocks any fibers that wait on
it. It is initialized with a positive integer n
latches and waiting
fibers are semantically blocked until all n
latches are released.
After this, further await
s are no-ops (equivalent to IO.unit
).
trait CountDownLatch[F[_]] {
def release: F[Unit]
def await: F[Unit]
}
Cancelation of await
is supported.
import cats.implicits._
import cats.effect._
import cats.effect.std.CountDownLatch
import cats.effect.unsafe.implicits.global
val run = (
for {
c <- CountDownLatch[IO](2)
f <- (c.await >> IO.println("Countdown latch unblocked")).start
_ <- c.release
_ <- IO.println("Before latch is unblocked")
_ <- c.release
_ <- f.join
} yield ()
)
// run: IO[Unit] = FlatMap(
// ioe = FlatMap(
// ioe = Map(
// ioe = Delay(
// thunk = cats.effect.IO$$$Lambda$16272/0x0000000803929c40@365bca3c,
// event = cats.effect.tracing.TracingEvent$StackTrace
// ),
// f = cats.effect.std.CountDownLatch$State$$$Lambda$16273/0x000000080392b040@1fb43357,
// event = cats.effect.tracing.TracingEvent$StackTrace
// ),
// f = cats.effect.std.CountDownLatch$$$Lambda$16274/0x000000080392b840@2bbd9324,
// event = cats.effect.tracing.TracingEvent$StackTrace
// ),
// f = <function1>,
// event = cats.effect.tracing.TracingEvent$StackTrace
// )
run.unsafeRunSync()