Created
April 14, 2020 14:40
-
-
Save fancellu/df6c4f9d8cd8cbd8ee53f73b74b704c1 to your computer and use it in GitHub Desktop.
Zio example of Semaphore usage
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
| start 3 | |
| start 1 | |
| end 1 | |
| end 3 | |
| start 2 | |
| end 2 | |
| List(101, 102, 103) | |
| // note, 1st 2 tasks start together because there are 2 permits |
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 zio._ | |
| import zio.clock._ | |
| import zio.console._ | |
| import zio.duration._ | |
| import java.util.concurrent.TimeUnit | |
| object Sem1 extends scala.App{ | |
| val runtime = Runtime.default | |
| val task: Int=> ZIO[Console with Clock, Nothing, Int] = i=> for { | |
| _ <- putStrLn(s"start $i") | |
| _ <- ZIO.sleep(Duration(2, TimeUnit.SECONDS)) | |
| _ <- putStrLn(s"end $i") | |
| } yield i+100 | |
| val semTask: Int=> Semaphore => ZIO[Console with Clock, Nothing, Int] = i=> (sem: Semaphore) => for { | |
| iplus100 <- sem.withPermit(task(i)) | |
| } yield iplus100 | |
| val semTaskSeq: Semaphore => IndexedSeq[ZIO[Console with Clock, Nothing, Int]] = (sem: Semaphore) => (1 to 3).map(semTask(_)(sem)) | |
| val program = for { | |
| sem<- Semaphore.make(permits = 2) | |
| seq <- ZIO.effectTotal(semTaskSeq(sem)) | |
| ipluses: Seq[Int] <- ZIO.collectAllPar(seq) | |
| } yield ipluses | |
| val ipluses: Seq[Int] =runtime.unsafeRunTask(program) | |
| println(ipluses) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment