Skip to content

Commit 995359e

Browse files
committed
Add a balancer example to README.md.
1 parent 1b1ff45 commit 995359e

File tree

2 files changed

+37
-1
lines changed

2 files changed

+37
-1
lines changed

README.md

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -338,6 +338,38 @@ Int received: 2
338338
String received: edef
339339
```
340340

341+
### A balancer example
342+
Here is example function that balances inputs from two channels into two output channels.
343+
Notice that `select()` is used to wait for any of the channels to have an incoming message, as well as
344+
to select a free output channel. You can mix `sender()` and `recver()` calls in the same `select()` statement.
345+
A finish channel is used to signal the end of the balancing process.
346+
347+
```scala
348+
def balancer(input1: ReadChannel[Int],
349+
input2: ReadChannel[Int],
350+
output1: WriteChannel[Int],
351+
output2: WriteChannel[Int],
352+
finishChannel: ReadChannel[Boolean]): Unit = {
353+
var v: Int = 0
354+
var exit = false
355+
356+
while (!exit) {
357+
select(
358+
input1.recver(x => v = x),
359+
input2.recver(x => v = x),
360+
finishChannel.recver(_ => exit = true)
361+
)
362+
363+
if (!exit) {
364+
select(
365+
output1.sender(v) {},
366+
output2.sender(v) {}
367+
)
368+
}
369+
}
370+
}
371+
```
372+
341373
### Scala-specific channel features
342374
Since Scala is a functional language, this implementation of channels supports functional operations used in for comprehension.
343375

src/test/scala/com/github/yruslan/channel/GuaranteesSuite.scala

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -125,7 +125,11 @@ class GuaranteesSuite extends AnyWordSpec {
125125
out2: com.github.yruslan.channel.Channel[Int]): Unit = {
126126
val results = new ListBuffer[(Int, Int)]
127127

128-
def balancer(input1: ReadChannel[Int], input2: ReadChannel[Int], output1: WriteChannel[Int], output2: WriteChannel[Int], finishChannel: ReadChannel[Boolean]): Unit = {
128+
def balancer(input1: ReadChannel[Int],
129+
input2: ReadChannel[Int],
130+
output1: WriteChannel[Int],
131+
output2: WriteChannel[Int],
132+
finishChannel: ReadChannel[Boolean]): Unit = {
129133
var v: Int = 0
130134
var exit = false
131135

0 commit comments

Comments
 (0)