Last active
May 27, 2022 23:11
-
-
Save russwyte/660f3572e29af2a80963dc74b0460d01 to your computer and use it in GitHub Desktop.
Semaphore Fun
This file contains 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 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