原文
通道是一个可用来连接协程,实现不同协程间通信的并发安全队列.
cpp
@Test
fun `test know channel`() = runBlocking<Unit> {
val channel = Channel<Int>()
//生产者
val producer = GlobalScope.launch {
var i = 0
while (true) {
delay(1000)
channel.send(++i)
println("send $i")
}
}
//消费者
val consumer = GlobalScope.launch {
while (true) {
val element = channel.receive()
println("receive $element")
}
}
joinAll(producer, consumer)
}
该示例很简单,生产者协程和消费者协程通过通道通信.
C++20协程有通道吗?与go和kotlin那样的通道.
答案是:有,就在yalantinglibs的coro_io里面.
来看看C++20协程通道的用法:
cpp
auto executor = coro_io::get_global_block_executor()->get_asio_executor();
asio::experimental::channel<void(std::error_code, int)> channel(executor, 1000);
co_await coro_io::async_send(ch, 42);
auto [ec, val] = co_await coro_io::async_receive<int>(channel);
assert(val == 42);
创建了个容量为1000的通道,后续就可通过该通道实现协程间通信了.
这就是C++20协程通道,用法和go,kotlin的通道类似.