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通道类似.

相关推荐
樱木Plus2 天前
深拷贝(Deep Copy)和浅拷贝(Shallow Copy)
c++
blasit3 天前
笔记:Qt C++建立子线程做一个socket TCP常连接通信
c++·qt·tcp/ip
肆忆_4 天前
# 用 5 个问题学懂 C++ 虚函数(入门级)
c++
不想写代码的星星5 天前
虚函数表:C++ 多态背后的那个男人
c++
端平入洛6 天前
delete又未完全delete
c++
端平入洛7 天前
auto有时不auto
c++
哇哈哈20218 天前
信号量和信号
linux·c++
多恩Stone8 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
蜡笔小马8 天前
21.Boost.Geometry disjoint、distance、envelope、equals、expand和for_each算法接口详解
c++·算法·boost
超级大福宝8 天前
N皇后问题:经典回溯算法的一些分析
数据结构·c++·算法·leetcode