卡卷网
当前位置:卡卷网 / 每日看点 / 正文

CPP26的exec模型你认为设计的如何?

作者:卡卷网发布时间:2025-03-05 22:04浏览数量:51次评论数量:0次

我觉得非常好。我第一时间能想到的有以下几个方面:

1、统一的异步模型,thread pool、GPU等这种资源调度以后都有了统一的调度接口,第三方库之间相互集成也变得更加方便。不仅仅是抽象出了scheduler/sender/receiver之类的接口,还封装了一些常用的异步算法,像when_all之类的,大大简化了异步代码的编写。

以前老有人问为什么STL中没有thread pool,其实只要就是因为C++还没有统一的异步模型,即使想要提供thread pool也没法确定需要提供什么样的api接口。现在不一样了,哪怕第三方的各种thread pool也可以轻松按照execution的模型来适配,stdexec里面就适配了好几个thread pool,包括tbb、asio等等:

CPP26的exec模型你认为设计的如何?  第1张

链接:

github.com/NVIDIA/stdex

2、协程和传统异步的高度统一,两种调用方式给你选择。协程方式主要是代码编写简单、可读性好,sender方式主要是可移植性更强,且性能更高。execution中的sender很容易就能支持co_await。

stdexec的文档中的这个例子:

CPP26的exec模型你认为设计的如何?  第2张

我把它协程,就变成这样:

#include <stdexec/execution.hpp> #include <exec/static_thread_pool.hpp> #include <exec/task.hpp> #include <print> exec::task<std::tuple<int, int, int>> Work(auto& scheduler) { auto fun = [](int i) { return i*i; }; auto work = stdexec::when_all( stdexec::on(scheduler, stdexec::just(0) | stdexec::then(fun)), stdexec::on(scheduler, stdexec::just(1) | stdexec::then(fun)), stdexec::on(scheduler, stdexec::just(2) | stdexec::then(fun)) ); co_return co_await work; } int main() { exec::static_thread_pool pool(3); auto scheduler = pool.get_scheduler(); auto work = Work(scheduler); auto [tp] = stdexec::sync_wait(std::move(work)).value(); // expect(tp == std::tuple<int, int, int>(0, 1, 4)); }

3、应用structured concurrency思想,并将其推向新的高度。作为asio的粉丝,我觉得asio输得不冤。asio::co_spawn是不符合structured concurrency思想的:

CPP26的exec模型你认为设计的如何?  第3张

youtube上有好几个关于Structured Concurrency思想的不错的视频,如果你只想看一个,我推荐这个:

youtube.com/watch?

90年代C++凭借STL+上百种算法取得了非常强大的竞争力。C++26的execution就是并行并发编程时代的STL,在所有编程语言里面继续领先,甚至遥遥领先。

END

免责声明:本文由卡卷网编辑并发布,但不代表本站的观点和立场,只提供分享给大家。

卡卷网

卡卷网 主页 联系他吧

请记住:卡卷网 Www.Kajuan.Net

欢迎 发表评论:

请填写验证码