gpt4 book ai didi

multithreading - 将 channel 桥接到序列

转载 作者:行者123 更新时间:2023-12-04 04:32:41 24 4
gpt4 key购买 nike

此代码基于 Coroutines guide example: Fan-out

val inputProducer = produce<String>(CommonPool) {
(0..inputArray.size).forEach {
send(inputArray[it])
}
}

val resultChannel = Channel<Result>(10)

repeat(threadCount) {
launch(CommonPool) {
inputProducer.consumeEach {
resultChannel.send(getResultFromData(it))
}
}
}

创建 Sequence<Result> 的正确方法是什么?这将提供结果?

最佳答案

您可以获得 channel .iterator() 来自 ReceiveChannel 然后将该 channel 迭代器包装成 Sequence<T> ,实现其正常Iterator<T>阻塞等待每个请求的结果:

fun <T> ReceiveChannel<T>.asSequence(context: CoroutineContext) =
Sequence {
val iterator = iterator()
object : AbstractIterator<T>() {
override fun computeNext() = runBlocking(context) {
if (!iterator.hasNext())
done() else
setNext(iterator.next())
}
}
}

val resultSequence = resultChannel.asSequence(CommonPool)

关于multithreading - 将 channel 桥接到序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45368353/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com