Tag: 通道

扇出/扇入结果通道

我正在生产项目,从多个协同例程中消费,并推回到resultChannel。 制片人正在关闭最后一个项目后的频道。 代码永远不会结束,因为resultChannel永远不会被关闭。 如何检测并正确完成迭代,所以hasNext()返回false ? val inputData = (0..99).map { "Input$it" } val threads = 10 val bundleProducer = produce<String>(CommonPool, threads) { inputData.forEach { item -> send(item) println("Producing: $item") } println("Producing finished") close() } val resultChannel = Channel<String>(threads) repeat(threads) { launch(CommonPool) { bundleProducer.consumeEach { println("CONSUMING $it") resultChannel.send("Result ($it)") } } } val iterator = object […]

Kotlin可以替代Python的协同产出和发送

什么是一个Kotlin惯用的替代下面的Python协程代码片段: def generator(): c = 1 while True: op = yield c if op == 'inc': c += 1 elif op == 'mult': c *= 2 # main g = generator() a = g.send(None) # start b = g.send('inc') c = g.send('mult') d = g.send('inc') print([a, b, c, d]) # 1, 2, 4, 5 所以我需要从协程(通过通道?)获取值,而且还要将值发送回协程。 […]