Skip to content

Instantly share code, notes, and snippets.

@russwyte
Last active May 27, 2022 23:11
Show Gist options
  • Save russwyte/660f3572e29af2a80963dc74b0460d01 to your computer and use it in GitHub Desktop.
Save russwyte/660f3572e29af2a80963dc74b0460d01 to your computer and use it in GitHub Desktop.
Semaphore Fun
import zio.*
import zio.Executor
import zio.Console.printLine
object CustomizedRuntimeZIOApp extends ZIOAppDefault:
val blockingTask = (n: Int) =>
for {
_ <- printLine(s"start potentially long API call or something for $n")
r <- Random.nextIntBetween(500, 1000)
_ <- ZIO.succeed(Thread.sleep(r))
_ <- printLine(s"end duration: $r for $n")
} yield n
val semTask = (n: Int, sem: Semaphore) =>
for {
n <- sem
.withPermit(blockingTask(n).debug(Thread.currentThread().getName))
} yield n
val semTaskSeq = (sem: Semaphore) => (1 to 1000000).map(n => semTask(n, sem))
val program = for {
sem <- Semaphore.make(permits = 5)
seq <- ZIO.succeed(semTaskSeq(sem))
_ <- ZIO.collectAllPar(seq)
} yield ()
def run = program
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment