2403C++,C++20协程通道

原文
通道是一个可用来连接协程,实现不同协程通信并发安全队列.

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协程有通道吗?与gokotlin那样的通道.

答案是:有,就在yalantinglibscoro_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通道类似.

相关推荐
hPw0eKIqD7 小时前
C++ 模板参数推导问题小记(非推导上下文)
开发语言·c++
程序员爱德华8 小时前
Python与C++:异同点对比
c++·python
888CC++11 小时前
C语言与C++的区别:从面向过程到面向对象
java·c语言·c++
Darkwanderor12 小时前
Linux系统编程实战项目:模拟实现shell
linux·c++
himobrinehacken13 小时前
揭秘Windows程序启动的神秘之旅
c++·安全
库玛西13 小时前
C++ 运行时多态 :核心总结与原理图解
c语言·c++·笔记
Byron Loong14 小时前
【C++】重定向是什么
开发语言·c++
hansang_IR15 小时前
【题解】LC:Z 算法(Z Algorithm)
c++·算法·字符串
霍霍的袁17 小时前
【C++】模板从入门到进阶(函数模板 + 类模板 + 特化 + 分离编译)
开发语言·c++·visual studio
海清河晏11117 小时前
Qt 实战:信号与槽+事件系统
开发语言·c++·qt