Created
July 20, 2023 12:44
-
-
Save adamw/3654fb89676bd90b27973c93e0e65e2f 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
//> using dep com.softwaremill.ox::core:0.0.7 | |
import ox.* | |
import ox.channels.* | |
import scala.annotation.tailrec | |
scoped { | |
// fast producer | |
val c = Channel[Int]() | |
fork { | |
forever { | |
c.send(1) | |
Thread.sleep(100) | |
} | |
} | |
// slow consumer | |
val d = Channel[Int]() | |
val consumer = fork { | |
forever { | |
println("Received: " + d.receive().orThrow) | |
Thread.sleep(1000) | |
} | |
} | |
// accumulator process | |
fork { | |
@tailrec def loop(acc: Int): Unit = | |
select(d.sendClause(acc), c.receiveClause).orThrow match | |
case d.Sent() => loop(0) | |
case c.Received(n) => loop(acc + n) | |
loop(0) | |
} | |
// unless there's an exception, this will never complete | |
consumer.join() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment