https://www.kotlincn.net/docs/reference/coroutines/channels.html#使用管道的素数
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
import kotlinx.coroutines.*
fun main() = runBlocking {
var cur = numbersFrom(2)
for (i in 1..10) {
val prime = cur.receive()
println("ddd")
cur = filter(cur, prime)
}
coroutineContext.cancelChildren() // 取消所有的子协程来让主协程结束
}
fun CoroutineScope.numbersFrom(start: Int) = produce<Int> {
var x = start
while (true) send(x++) // 从 start 开始过滤整数流
}
fun CoroutineScope.filter(numbers: ReceiveChannel<Int>, prime: Int) = produce<Int> {
println()
println("============" + prime + "============")
for (x in numbers) {
print(x.toString() + "," + "prime="+prime+", ")
if (x % prime != 0) {
send(x)
}
}
}
---------------result-----------------
ddd
============2============
3,prime=2, ddd
4,prime=2, 5,prime=2,
============3============
5,prime=3, 6,prime=2, ddd
============5============
7,prime=2, 8,prime=2, 7,prime=3, 7,prime=5, 9,prime=2, 10,prime=2, ddd
9,prime=3,
============7============
11,prime=2, 12,prime=2, 11,prime=3, 11,prime=5, 13,prime=2, 14,prime=2, 11,prime=7, 13,prime=3, ddd
13,prime=5, 15,prime=2, 16,prime=2,
============11============
13,prime=7, 15,prime=3, 13,prime=11, 17,prime=2, 18,prime=2, ddd
17,prime=3,
============13============
17,prime=5, 19,prime=2, 20,prime=2, 17,prime=7, 19,prime=3, 17,prime=11, 19,prime=5, 21,prime=2, 22,prime=2, 17,prime=13, 19,prime=7, 21,prime=3, ddd
19,prime=11, 23,prime=2, 24,prime=2,
============17============
19,prime=13, 23,prime=3, 19,prime=17, 23,prime=5, 25,prime=2, 26,prime=2, ddd
23,prime=7, 25,prime=3,
============19============
23,prime=11, 25,prime=5, 27,prime=2, 28,prime=2, 23,prime=13, 27,prime=3, 23,prime=17, 29,prime=2, 30,prime=2, 23,prime=19, 29,prime=3, ddd
29,prime=5, 31,prime=2, 32,prime=2,
============23============
29,prime=7, 31,prime=3, 29,prime=11, 31,prime=5, 33,prime=2, 34,prime=2, 29,prime=13, 31,prime=7, 33,prime=3, 29,prime=17, 31,prime=11, 35,prime=2, 36,prime=2, 29,prime=19, 31,prime=13, 35,prime=3, 29,prime=23, 31,prime=17, 35,prime=5, 37,prime=2, 38,prime=2, ddd
31,prime=19, 37,prime=3,
small modified
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
import kotlinx.coroutines.*
fun main() = runBlocking {
var cur = numbersFrom(2)
for (i in 1..10) {
val prime = cur.receive()
println("ddd")
cur = filter(cur, prime)
}
coroutineContext.cancelChildren() // 取消所有的子协程来让主协程结束
}
fun CoroutineScope.numbersFrom(start: Int) = produce<Int> {
var x = start
while (true) send(x++) // 从 start 开始过滤整数流
}
fun CoroutineScope.filter(numbers: ReceiveChannel<Int>, prime: Int) = produce<Int> {
println("<>")
println("============" + prime + "============")
for (x in numbers) {
print(x.toString() + "," + "prime="+prime+", ")
if (x % prime != 0) {
send(x)
delay(10)
}
}
}